使用函数redux-thunk时,返回函数action报错
来源:9-7 【中间件】使用redux-thunk中间价实现异步action

程序员班吉
2024-04-11
// recommentProductsActions.ts
export type RecommendProductAction =
| FetchRecommendProductsStartAction
| FetchRecommendProductsSuccessAction
| FetchRecommednProductsFailAction;
...
export const giveMeDataActionCreator = (): ThunkAction<
void,
RootState,
unknown,
RecommendProductAction
> => async (dispatch: Dispatch, getState) => {
dispatch(fetchRecommendProductsStartActionCreater())
try {
const { data } = await axios.get("http://82.157.43.234:8080/api/productCollections")
dispatch(fetchRecommendProductsSuccessActionCreator(data))
} catch (e) {
if (e instanceof Error) {
dispatch(fetchRecommednProductsFailActionCreator(e.message))
}
}
}
// homePage.tsx
const mapDispatchToProps = (dispatch: Dispatch) => {
return {
giveData: () => {
dispatch(giveMeDataActionCreator())
}
}
}
dispatch(giveMeDataActionCreator()) 报错如下:
Argument of type ‘ThunkAction<void, EmptyObject & { language: LanguageState; recommendProducts: { loading: boolean; productList: any; error: string | null; } | { loading: boolean; error: any; productList: any[]; }; }, unknown, RecommendProductAction>’ is not assignable to parameter of type ‘AnyAction’.ts(2345)
(alias) giveMeDataActionCreator(): ThunkAction<void, EmptyObject & {
language: LanguageState;
recommendProducts: {
loading: boolean;
productList: any;
error: string | null;
} | {
loading: boolean;
error: any;
1回答
-
程序员班吉
提问者
2024-04-11
这个问题是由于
// homePage.tsx const mapDispatchToProps = (dispatch: Dispatch) => { return { giveData: () => { dispatch(giveMeDataActionCreator()) } }
dispatch参数类型不一致导致的,这里应该要用redux-thunk中的ThunkDispatch,或者不写,像下面这样:
const mapDispatchToProps = (dispatch) => {
return {
giveData: () => {
dispatch(giveMeDataActionCreator())
}
}
}
00
相似问题