我需要使用useAppDispatch来等待调度异步thunk操作
interface AppDispatch<A extends Action = AnyAction> {
<T extends A | Function>(action: T): T extends Function ? Promise<AnyAction> : T;
}
function useAppDispatch(): AppDispatch {
return useDispatch();
}
Iam调度动作为
appDispatch(fetchSocialPagePermissions()).then((pagesResponse) => {
const facebookConnectedPages = pagesResponse?.payload?.facebookPageResponse?.pages;
if (facebookConnectedPages && facebookConnectedPages.length > 0) {
dispatch(exportCollateral({fulfillmentType: FulfillmentType.SHARE_INSTAGRAM}));
}
});
问题是,有严格的打字脚本检查,我收到这个
Don't use `Function` as a type. The `Function` type accepts any function-like value.
It provides no type safety when calling the function, which can be a common source of bugs.
如何给出函数的类型?
请遵循Redux和RTK文档中显示的TS应用程序设置方法,特别是从store.dispatch
推断AppDispatch
类型并创建useAppDispatch
挂钩的过程:
// app/store.ts
import { configureStore } from '@reduxjs/toolkit'
// ...
const store = configureStore({
reducer: {
one: oneSlice.reducer,
two: twoSlice.reducer
}
})
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
// app/hooks.ts
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import { RootState, AppDispatch } from './store'
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
然后,AppDispatch
类型将理解可以调度thunk,并且thunk返回值将从dispatch
返回,从而允许执行dispatch(someThunk()).then()
。