我正在尝试更新部分redux状态,该状态包含嵌套在另一个对象内的两个对象。通常,当一成不变地更新javascript对象时,我会使用spread运算符,然后按如下所示定义所有更改:
state = {...state, property1: newvalue}
但是,当我嵌套对象时,不确定如何使用散布运算符。这是相关的代码和我的尝试:
const squadDatabase = {currentSquad: {
0: null,
1: null,
2:null
}, newAdditions: null}
export default (state=initial_squad, action)=>{
switch(action.type){
case ADD_PLAYER_TO_SQUAD:
return {...state, currentSquad[action.payload.currentSquadMemberId]:action.payload.newSquadAdditionId, newAdditions: action.payload.newSquadAdditionId}
default:
return initial_squad
}
}
有人知道如何使用传播运算符或其他方法不变地更新嵌套的javascript对象吗?
答案 0 :(得分:2)
基本上,您必须添加第二级对象(状态)解构。
return {
...state, // first nesting level spread
currentSquad: {
...this.state.currentSquad, // second nesting level spread
currentSquad[action.payload.currentSquadMemberId]: action.payload.newSquadAdditionId,
},
newAdditions: action.payload.newSquadAdditionId,
};