gpt4 book ai didi

reactjs - 如何在 redux-toolkit 中正确使用带有元类型的 PayloadAction?

转载 作者:行者123 更新时间:2023-12-04 12:40:03 25 4
gpt4 key购买 nike

简化示例

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 的默认行为是创建一个只有一个参数和一个有效载荷属性的 Action 创建者。 TS 注释无法修改此行为,因为 TS 注释对运行时行为没有影响。

您可以使用 the prepare notation定义一个覆盖此默认行为的函数。
此函数具有与 prepare argument for 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 } }
}
}
}
})


这是一个 typescript playground

关于reactjs - 如何在 redux-toolkit 中正确使用带有元类型的 PayloadAction?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60320668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com