简体   繁体   English

Array.map 使用箭头函数在 redux 减速器中返回 null

[英]Array.map returns null in a redux reducer using arrow functions

Consider this array of items:考虑这个项目数组:

items:[
 {
  _id: '111',
  quantity: 3
 },
 {
  _id: '222',
  quantity: 7
 }
]

I need to increment the value by 1 by looping using Array#map with CURLY BRACES following the arrow => (look at the code below), but this make the myNewItems null, and I guess this is because the variable item gets lost along the way and ends up with myNewItems to be null我需要通过使用Array#map和 CURLY BRACES 沿着箭头 => 循环来将值增加 1(请看下面的代码),但这使得 myNewItems null,我猜这是因为变量 item 在最终以 myNewItems 为 null

This is how I have iterated in a redux reducer这就是我在 redux 减速器中迭代的方式

return {
  ...state,
  myNewItems: items.map((item) => {
    var itemId = '111'

    item._id == itemId ?
      {
        ...item,
        quantity: item.quantity + 1
      } :
      item
  })
}

Now this makes myNewItems to be null instead of it having updated array of items like this below现在这使得 myNewItems 成为 null 而不是像下面这样更新项目数组

items:[
 {
  _id: '111',
  quantity: 4 //has been incremented by 1
 },
 {
  _id: '222',
  quantity: 7
 }
]

How do I get through this?我该如何度过这个难关?

You are missing the return statement in your map callback.您在map回调中缺少return语句。

items.map(
           (item) =>{
              var itemId = '111'
              return item._id == itemId?
              {...item, quantity: item.quantity + 1
              }:item
        })

missing return in map higher order function try this map 高阶 function 中缺少返回试试这个

return item._id == itemId
    ?{...item, quantity: item.quantity + 1}
    :item

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM