如何使用对象传播 reduxjs/toolkit

How to use object spread reduxjs/toolkit

我正在尝试将 @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 更改为 code

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

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

在这种情况下,您应该 return 来自函数的新对象:

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

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

you need to ensure that you either mutate the state argument or return a new state, but not both.