首页 > 解决方案 > 如何使用对象传播 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,
      };
    },
  },
});

当我将状态分配给新对象时,我的商店不会更新。但是,如果我将减速器更改为代码

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

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

标签: reactjsreduxredux-toolkit

解决方案


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

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

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

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


推荐阅读