reactjs - 如何在 redux-toolkit 中正确使用带有元类型的 PayloadAction?
问题描述
简化示例
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; }; }
'.
解决方案
RTK 的默认行为是创建一个只有一个参数和一个有效负载属性的动作创建者。TS 注释无法修改此行为,因为 TS 注释对运行时行为没有影响。
您可以使用该prepare
符号定义一个覆盖此默认行为的函数。prepare
此函数与createAction的参数具有相同的签名和行为,因此您可以在那里找到大部分相关文档。
在你的具体情况下,你会想要一些类似的东西
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 } }
}
}
}
})
这是一个打字稿游乐场
推荐阅读
- android - AppCompat 的问题
- javascript - 我想将 javascript 上传到我的潜在客户页面
- javascript - 使用多条弧线从图像中裁剪圆圈
- functional-programming - 如何以非阻塞方式解析 Spring 5 WebClient 响应?
- variables - ErrorException [注意]:动态构建的现有变量上的未定义变量
- haskell - 堆栈构建导致“输出已使用 -o 重定向,但不会生成输出,因为没有主模块。”
- java - 如何在 Cucumber 报告中为所采取的每项操作嵌入屏幕截图?
- sql - 在oracle sql中设置连接的用户名密码
- html - 浏览器未将链接解析为链接
- java - 单例、线程和同步