有时,当我运行loadPosts调度时,我不发送任何数据,有时我将lastId数据发送到相同的loadPosts调度。
此时我不知道如何定义 createAsyncThunk 中的数据类型。 当我运行代码时,我在 loadPosts 中收到红色警告。
喜欢这个截图
它说 预期有 1 个参数,但得到了 0 个。
如何修复我的代码?
这是我的代码
dispatch(loadPosts());
dispatch(loadPosts(lastId:lastId));
export const loadPosts = createAsyncThunk(
'post/loadPosts',
async (data: any, thunkAPI) => {
try {
const response = await axios.get(`/post?lastId=${data?.lastId || 0}`);
return response.data;
} catch (error: any) {
return thunkAPI.rejectWithValue(error.response.data);
}
},
最佳答案
RTK 文档:https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk
export const loadPosts = createAsyncThunk<
YourReturnType,
{
lastId: number;
} | void,
{ state: AppStore }
>('post/loadPosts', async (data, thunkAPI) => {
try {
const response = await axios.get(`/post?lastId=${data?.lastId || 0}`);
return response.data;
} catch (error) {
return thunkAPI.rejectWithValue(error.response.data);
}
});
关于javascript - 我应该如何设置 createAsyncThunk 中的参数和参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72070647/