Return 具有动态密钥的不可变状态

Return immutable state with a dynamic key

我正在使用 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
)

我怎样才能 return 状态的副本而不用 action.userId 作为 showModal 的键来改变它?

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

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

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