在我的 reducer 状态下,我有数组
grounds: [
{
name: 'name1',
id: 123
}
{
name: 'name2',
id: 456
}
{
name: 'name3',
id: 789
}
]
我正在调度一个如下所示的操作
export const renameGound = (newName, id) => {
return{
type: RENAME_GROUND,
newName: newName,
id: id
}
}
我想要的是将名称值更新为具有我作为 action.id 获得的 id 的对象。这是我尝试过的方法,但行不通。
case actionTypes.RENAME_GROUND:
return{
...state,
grounds: state.grounds.forEach(el => {
if(el.id === action.id){
el.name = action.newName
}
})
}
我错误地在上面的情况下放置了加载程序,而不是理由,它起作用了,我不知道如何起作用,但它起作用了。但是当我像这样尝试时却没有......
如何以正确的方式更新正确的对象?
最佳答案
你能尝试一下reducer中的下一个代码吗?
return {
...state,
grounds: state.grounds.map(el => {
if (el.id === action.id) {
return {
...el,
name: action.newName
};
}
return el;
})
};
reducer 保持纯净非常重要。你永远不应该改变它的内部参数。
更多信息可以在 Redux documentation 中找到
关于javascript - 更新reducer中的数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57545279/