【问题标题】:How to use spread operator on nested javascript objects?如何在嵌套的 javascript 对象上使用扩展运算符?
【发布时间】:2020-03-15 13:00:42
【问题描述】:

我正在尝试更新我的部分 redux 状态,其中包含嵌套在另一个对象中的两个对象。通常在不可变地更新 javascript 对象时,我会使用扩展运算符,然后定义任何更改,如下所示:

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 对象?

【问题讨论】:

标签: javascript reactjs object redux spread


【解决方案1】:

基本上你必须添加第二级对象(状态)解构。

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

【讨论】:

    猜你喜欢
    • 2021-01-15
    • 2021-07-07
    • 2020-03-18
    • 1970-01-01
    • 2019-04-26
    • 2020-06-09
    • 2017-09-20
    • 2017-03-17
    • 2020-10-04
    相关资源
    最近更新 更多