我有这个thunk Package 器,我最初在js应用程序中使用。
因此,我很难弄清楚如何键入它,主要是因为thunk
和thunkApi
类型:
export const asyncThunkHandleError = (
typePrefix: string,
thunk: any, // how to type this one and thunkAPI?
errorMessage?: string
) =>
createAsyncThunk(typePrefix, async (arg: any, thunkAPI: any) => {
try {
// actually call the thunk
return await thunk(arg, thunkAPI);
} catch (error: any) {
// here we will dispatch the modal with the error message
thunkAPI.dispatch(
openModal({
title: `Error in ${typePrefix}`,
children: `${error instanceof Error ? error.message : 'Unknown error'}`,
})
);
throw thunkAPI.rejectWithValue(error.response?.data || errorMessage);
}
});
它的调度方式如下:
// SomeComponent.tsx
dispatch(getPokemons());
thunk是这样 Package 的:
// actions/pokemons.ts
const getPokemons = asyncThunkHandleError(
'pokemons/getPokemons',
async (arg: any, thunkAPI: any) => {
const someNetworkCall = await fetch('https://example.com');
return someNetworkCall.json();
},
'An error occurred'
);
我一直在检查依赖文件,在路径.../@reduxjs/toolkit/src/createAsyncThunk.ts
中发现了一些类型,如BaseThunkAPI
、GetThunkAPI
、AsyncThunkPayloadCreator
等,但我不确定如何实现它,也不确定它是否正确。
1条答案
按热度按时间slwdgvem1#
好吧,我找到了一个类似here情况的解决方案,它甚至有一个操场: