我似乎不能接收来自createAsyncThunk函数的Promise来自Redux-toolkit我对Typescript还很陌生,我在努力弄清楚为什么它会给我Property 'then' does not exist on type 'AsyncThunkAction<Student, number, {}>'错误,即使如果我删除键入就会返回promise。这是我的createAsyncThunk f-n
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
}
}
)这就是我从React组件中分派它的方式
dispatch(getStudentByIdRequest(userId)).then((res) => console.log(res))错误出现在我尝试在thunk上调用then的地方
发布于 2020-09-09 20:40:47
您的dispatch没有考虑thunks的类型,因此返回类型输入不正确。请使用在the documentation中描述的存储中的实际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然后在组件中使用useAppDispatch而不是useDispatch。
发布于 2021-07-12 16:07:53
另一种可能的解决方案是使用ThunkDispatch类型而不是普通的Dispatch,因为普通的Dispatch并不意味着要处理异步的东西。
在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>();然后你可以在你的应用中使用useAppThunkDispatch钩子,就像useAppDispatch或者useDispatch钩子一样。
https://stackoverflow.com/questions/63811401
复制相似问题