在我的 redux reducer 状态下,我想更新对象对象中的属性。
{
users:{
'1':{id:'1', name:'', items:[], ....}
'2':{id:'1', name:'', items:[], ....}
...
}
}
例如,我只想使用键1 or 2
或任何其他键更新对象中的items
,其余状态保持不变。 该操作包含键编号作为action.id
,action.payload
包含字符串。
我感到困惑的是spread
和update
是如何工作的,以及如何保持其余users
物体不变。
当然我的代码是错误的:)但我试过了
case types.UPDATE_ITEMS: {
return update(...state, {
[action.id]: { items: { $set: action.payload } }
});
}
这正是update
的用法,它将保持状态的其余部分不变。 所以不需要传播
case types.UPDATE_ITEMS:
return update(state, {
[action.id]: {
items: { $set: action.payload }
}
});
您可以使用其余扩展运算符仅更新users
部分,如下所示:
case types.UPDATE_ITEMS:
return {
...state, // That will keep any other keys in the object besides 'users'
users: {
...state.users, // keep the part you want to keep from 'users',
[action.id]: {
...state.users[action.id], // keep the part you want from this user
items: [action.payload] // update the part you want
}
}
};