React Redux,使用不可变性辅助程序更新更新部分状态



在我的 redux reducer 状态下,我想更新对象对象中的属性。

{
users:{
'1':{id:'1', name:'', items:[], ....}
'2':{id:'1', name:'', items:[], ....}
...
}
}

例如,我只想使用键1 or 2或任何其他键更新对象中的items,其余状态保持不变。 该操作包含键编号作为action.idaction.payload包含字符串。

我感到困惑的是spreadupdate是如何工作的,以及如何保持其余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
}
}
};

最新更新