考虑这个项目数组:
items:[
{
_id: '111',
quantity: 3
},
{
_id: '222',
quantity: 7
}
]
我需要通过使用 Array#map
循环将值增加 1,并在箭头 => 之后使用大括号(请查看下面的代码),但这会使 myNewItems 为空,我猜这是因为变量 item 在途中丢失并最终 myNewItems 为 null
这就是我在 redux reducer 中迭代的方式
return {
...state,
myNewItems: items.map((item) => {
var itemId = '111'
item._id == itemId ?
{
...item,
quantity: item.quantity + 1
} :
item
})
}
现在这使得 myNewItems 为空,而不是像下面这样更新项目数组
items:[
{
_id: '111',
quantity: 4 //has been incremented by 1
},
{
_id: '222',
quantity: 7
}
]
我该如何度过这个难关?
最佳答案
您在 map
回调中缺少 return
语句。
items.map(
(item) =>{
var itemId = '111'
return item._id == itemId?
{...item, quantity: item.quantity + 1
}:item
})
关于javascript - Array.map 使用箭头函数在 redux reducer 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62747423/