【问题标题】:How to use object spread reduxjs/toolkit如何使用对象传播 reduxjs/toolkit
【发布时间】:2020-12-14 13:19:56
【问题描述】:

我正在尝试在我的项目中实现 @reduxjs/toolkit,目前我在使用扩展运算符时遇到了问题

const initialState: AlertState = {
  message: '',
  open: false,
  type: 'success',
};

const alertReducer = createSlice({
  name: 'alert',
  initialState,
  reducers: {
    setAlert(state, action: PayloadAction<Partial<AlertState>>) {
      state = {
        ...state,
        ...action.payload,
      };
    },
  },
});

当我将状态分配给新对象时,我的商店不会更新。 但是如果我把reducer改成代码

state.message = action.payload.message || state.message;
state.open = action.payload.open || state.open;

但这不是很方便。那么有没有办法使用扩展运算符?

【问题讨论】:

    标签: reactjs redux redux-toolkit


    【解决方案1】:

    在这种情况下,您应该从函数中返回新对象:

        setAlert(state, action: PayloadAction<Partial<AlertState>>) {
          return {
            ...state,
            ...action.payload,
          };
        },
    

    您可以在docs 中查看更多示例。 另外,请注意这条规则:

    您需要确保更改状态参数或返回新状态,但不能同时更改两者。

    【讨论】:

    • 我花了几个小时才明白我正在混合变异并使用扩展运算符做一个新状态。由于这个问题的浏览量很少,恐怕还有人在寻找解决方案?
    猜你喜欢
    • 2021-10-03
    • 2022-01-01
    • 2021-12-15
    • 1970-01-01
    • 2020-03-22
    • 2021-05-19
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多