使用动态密钥

时间:2016-05-01 20:53:28

标签: javascript immutability redux

我正在使用Redux,我的商店看起来像这样

const initialState = {
  'ui': {
    'showModal': {}, // contains the `userId`: true || false
  }
}

我的减速机看起来像

case actions.OPEN_MODAL:
return Object.assign(
  {},
  state,
  state.ui.showModal[action.userId] = true // <- I think it is actually mutating instead of returning a copy of the state
)

如何使用action.userId作为showModal的关键字返回状态副本而不是将其变更?

1 个答案:

答案 0 :(得分:4)

是的,你正在改变。相反,您应该分配一个新对象来执行此操作:

const newState = {
    ui: {
        showModal: {},
    }
};
newState.ui.showModal[action.userId] = true;

return Object.assign(
    {},
    state,
    newState,
)