如何在 redux-toolkit 中输入 'prepare' 函数

How to type 'prepare' function in redux-toolkit

我正在使用 redux-toolkit prepare 函数来构建最终的负载值。

    addTodo: {
      reducer: (state, action) => {
        state.push(action.payload);
      },
      // ERROR: **Type '{ payload: Todo; }' is missing the following properties from type 'Omit<PayloadAction<any, string, any, any>, "type">': meta, errorts**
      prepare: (todoMessage: string): { payload: Todo } => {
        return {
          payload: { message: todoMessage, id: uuid(), completed: false }
        };
      }
    },

如何键入 prepare 函数来消除 typescript 错误?

检查错误here

type DefaultPayload = any;`

在你的减速器中定义整个状态

type WholeState = {
    count: number;
    ...
};

将操作定义为开始计数

let startCount = createStandardAction<WholeState> ('actionType')<DefaultPayload>();

然后在你的 store side reducer 中,结合 startCount 到 empty action。

const reducer = createReducer<WholeState, typeof startCount>(initialState,
  builder => builder.addCase(startCount, (state, action) = {
      return {
        count: state.count + 1
      }
    })
  )

完整示例:

let startCount = createStandardAction<WholeState> ('demo/count-started')<;DefaultPayload>();

type WholeState = {
    count: number;
};

let initialState :WholeState= {
    count: 0
};

const reducer = (state: WholeState, action: AnyAction) =>; createReducer<WholeState, typeof startCount>(initialState,
    builder => builder.addCase(startCount, (state, action) => {
        return {
            count: state.count + 1
        }
    })
).caseReducer(state, action)

这个工作不错。

    addTodo: {
      reducer: (state, action: PayloadAction<Todo>) => {
        state.push(action.payload);
      },
      prepare: (todoMessage: string) => {
        return {
          payload: { message: todoMessage, id: uuid(), completed: false }
        };
      }
    },

您只需要在 action.

上添加一个负载类型