如何在redux-toolkit中正确使用 meta类型的PayloadAction?

ie3xauqp  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(130)

简化示例

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

    type Cake = {
      flavor: string;
      size: 'S' | 'M' | 'L';
    };

const initialState: { all: Cake[]; meta: { currentPage: number } } = {
  all: [],
  meta: {
    currentPage: 0,
  },
};

const cakeSlice = createSlice({
  name: 'cake',
  initialState,
  reducers: {
    fetchAll(
      state,
      action: PayloadAction<Cake[], string, { currentPage: number }>,
    ) {
      state.all = action.payload;
      state.meta = action.meta;
    },
  },
});

export default cakeSlice;

我得到了这些错误。

Type '
(state: {
    all: {
        flavor: string;size: "S" | "M" | "L";
    } [];meta: {
        currentPage: number;
    };
}, action: PayloadAction < Cake[], string, {
    currentPage: number;
}, never > ) => void ' is not assignable to type '
CaseReducer < {
    all: Cake[];meta: {
        currentPage: number;
    };
}, {
    payload: any;type: string;
} > | CaseReducerWithPrepare < {
    all: Cake[];meta: {
        currentPage: number;
    };
}, {
    payload: any;type: string;
} > '
Type '
(state: {
    all: {
        flavor: string;size: "S" | "M" | "L";
    } [];meta: {
        currentPage: number;
    };
}, action: PayloadAction < Cake[], string, {
    currentPage: number;
}, never > ) => void '
is not assignable to type 'CaseReducer<{ all: Cake[]; meta: { currentPage: number; }; }, { payload: any; type: string; }>'.
Types of parameters 'action'
and 'action'
are incompatible.
Type '{ payload: any; type: string; }'
is not assignable to type 'PayloadAction<Cake[], string, { currentPage: number; }, never>'.
Property 'meta'
is missing in type '{ payload: any; type: string; }'
but required in type '{ meta: { currentPage: number; }; }
'.
k3fezbri

k3fezbri1#

RTK的默认行为是创建一个只有一个参数和一个有效负载属性的动作创建器。TS注解不能修改此行为,因为TS注解对运行时行为没有影响。
您可以使用prepare表示法来定义一个覆盖此默认行为的函数。此函数与createAction的prepare参数具有相同的签名和行为,因此您可以在那里找到大部分相关文档。
在你的特殊情况下,你会想要一些沿着的东西

const cakeSlice = createSlice({
  name: 'cake',
  initialState,
  reducers: {
    fetchAll: {
      reducer(
        state,
        action: PayloadAction<Cake[], string, { currentPage: number }>
      ) {
        state.all = action.payload
        state.meta = action.meta
      },
      prepare(payload: Cake[], currentPage: number) {
        return { payload, meta: { currentPage } }
      }
    }
  }
})

这里是一个打字游戏场

相关问题