Array.map使用箭头函数在redux reducer中返回null

时间:2020-07-05 23:37:32

标签: javascript arrays redux

请考虑以下数组:

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

我需要通过使用Array#map并在箭头=>之后使用return { ...state, myNewItems: items.map((item) => { var itemId = '111' item._id == itemId ? { ...item, quantity: item.quantity + 1 } : item }) } 并在CURLY括号中循环来使值增加1(请看下面的代码),但这会使myNewItems为null,我想这是因为变量项目在途中迷路,最终以myNewItems为空

这就是我在redux reducer中进行迭代的方式

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

现在,这会使myNewItems为null,而不是像下面这样更新项数组

def string_error_raiser(s):
    if 'k' in s:
        raise ValueError("The string contains the letter 'k'!")
    elif 'l' in s:
        raise KeyError("The string contains the letter 'l'!")

我如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

您在return回调中缺少map语句。

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

答案 1 :(得分:-1)

缺少地图高阶函数的返回 试试这个

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