使用动态键返回不可变状态

Return immutable state with a dynamic key

本文关键字:不可变 状态 返回 动态      更新时间:2023-09-26

我正在使用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的密钥对其进行更改?

是的,你正在变异。相反,您应该分配一个新对象来执行此操作:
const newState = {
    ui: {
        showModal: {},
    }
};
newState.ui.showModal[action.userId] = true;
return Object.assign(
    {},
    state,
    newState,
)