如何在 redux 工具包中推送到 reducer 状态的数组值?

How to push to array value of reducer state in redux toolkit?

我有一个简单的reducer函数

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { TSnackBarProps } from 'plugins/notification/NotificationContext';
import { MAX_STACK } from 'plugins/notification/NotificationsStack';

interface INotificationState {
  notifications: TSnackBarProps[];
}

const initialState: INotificationState = {
  notifications: [],
};

const notificationSlice = createSlice({
  name: 'notification',
  initialState,
  reducers: {
    addNewNotification(state, action: PayloadAction<TSnackBarProps>) {
      const { notifications } = state;
      const { payload: notification } = action;
      if (notifications.find((n) => n.severity === notification.severity && n.key === notification.key)) {
        return;
      }
      if (notifications.length >= MAX_STACK) {
        notifications.splice(0, notifications.length - MAX_STACK);
      }

      state.notifications.push(notification);
    },
  },
});
export default notificationSlice.reducer;

但是,它会抛出如下所示的错误:

我刚开始写这个 reducer 就卡在这里了。感谢您的帮助。

此外,TSnackBarProps 只是 material-ui 的 SnackBarProps 类型,添加了严重性 属性。

RTK使用的

immerDraft类型暂时从所有状态类型中删除readonly,以便您可以自由修改它。不幸的是,在这种情况下,这有点过头了。

但当然:你比 TypeScript 更了解这里。因此,您可以将当前为 Draft<INotificationState> 的状态变量转换为 INotificationState 以分配给它,在这种情况下,这是完全有效的做法。