Ale*_*min 2 reactjs redux redux-thunk redux-toolkit
我似乎无法从
我对 Typescript 相当陌生的人那里收到PromisefromcreateAsyncThunk函数Redux-toolkit,我正在努力弄清楚为什么它会给我
Property 'then' does not exist on type 'AsyncThunkAction<Student, number, {}>'错误,即使如果我删除打字,承诺确实会返回。这是我的createAsyncThunkfn
export const getStudentByIdRequest = createAsyncThunk<Student, number>(
'student/getStudentByIdRequest',
async (id, { rejectWithValue }) => {
try {
const { data } = await instance.get(`student/${id}/`)
return data
} catch (err) {
let error: AxiosError = err
if (error) {
return rejectWithValue({
message: `Error. Error code ${error.response?.status}`,
})
}
throw err
}
}
)
Run Code Online (Sandbox Code Playgroud)
这就是我从React组件中发送它的方式
dispatch(getStudentByIdRequest(userId)).then((res) => console.log(res))
Run Code Online (Sandbox Code Playgroud)
错误出现在我尝试调用thenthunk 的地方
Sho*_*ota 21
另一个潜在的解决方案可能是使用ThunkDispatchtype 而不是 plain Dispatch,因为 plainDispatch并不意味着处理异步内容。
在 store.ts 中定义可重用的useAppThunkDispatch钩子:
import { Action, ThunkDispatch, configureStore } from '@reduxjs/toolkit';
export const store = configureStore({
reducer: {
blog: blogSlice,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type ThunkAppDispatch = ThunkDispatch<RootState, void, Action>;
export const useAppThunkDispatch = () => useDispatch<ThunkAppDispatch>();
Run Code Online (Sandbox Code Playgroud)
然后,您可以在应用程序中使用useAppThunkDispatchhook,就像useAppDispatch或useDispatchhook 一样。
您dispatch没有考虑 thunk 的类型,因此返回类型的类型不正确。请使用文档中描述Dispatch的商店中的实际类型:
import { configureStore } from '@reduxjs/toolkit'
import { useDispatch } from 'react-redux'
import rootReducer from './rootReducer'
const store = configureStore({
reducer: rootReducer
})
export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>() // Export a hook that can be reused to resolve types
Run Code Online (Sandbox Code Playgroud)
然后在您的组件中使用useAppDispatch而不是useDispatch。
| 归档时间: |
|
| 查看次数: |
5112 次 |
| 最近记录: |