如何在嵌套javascript对象上使用扩展运算符?

时间:2019-11-19 22:17:58

标签: javascript reactjs object redux spread

我正在尝试更新部分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对象吗?

1 个答案:

答案 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,
};