Dispatch未使用带有typescript的redux thunk返回承诺
实际上,我正在将一些代码迁移到typescript,所以我对所有这些类型的东西都是新手。当我将redux thunk与常规javascript一起使用时,dispatch方法返回一个承诺,帮助我处理错误和其他问题。行动是这样的:Dispatch未使用带有typescript的redux thunk返回承诺,typescript,redux,redux-thunk,Typescript,Redux,Redux Thunk,实际上,我正在将一些代码迁移到typescript,所以我对所有这些类型的东西都是新手。当我将redux thunk与常规javascript一起使用时,dispatch方法返回一个承诺,帮助我处理错误和其他问题。行动是这样的: export const login = ({email, password}) => { return async function (dispatch) { try { const result = await
export const login = ({email, password}) => {
return async function (dispatch) {
try {
const result = await api.post(`/auth/login`, {username, password});
return dispatch({type: 'set_user_session', payload: result.data});
} catch (err) {
throw (err.response && err.response.data) || {code: err};
}
};
};
然后我正常使用useDispatch钩子调用:
const dispatch = useDispatch();
...
dispatch(login({username: "admin", password: "adminpassword1"}))
.then(d => console.log("ok"))
.catch(err => console.log(err));
现在,我已将代码迁移到typescript,操作如下所示:
export const login = ({username, password}: Credentials): ThunkAction<Promise<Action>, {}, {}, AnyAction> => {
// Invoke API
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>): Promise<Action> => {
try {
const result = await api.post(`/auth/login`, {username, password});
return dispatch({type: 'set_user_session', payload: result.data});
} catch (err) {
console.log(err);
throw (err.response && err.response.data) || {code: err};
}
}
}
我得到这个错误:
TS2339: Property 'then' does not exist on type 'ThunkAction >, {}, {}, AnyAction>'
我试图阅读关于Redux中类型的部分,但是我找不到正确的方法来声明这个分派函数在我需要的时候工作
更糟糕的是,在执行操作后,我遇到了以下运行时错误:
Possible Unhandled Promise Rejection (id: 0):
所以承诺就在某个地方。基本的
分派类型不知道thunks。您需要推断修改后的store.dispatch
类型,该类型告诉TS thunk是可接受的,然后它将理解分派thunk实际上返回一个承诺
这里最好的选择是切换到使用我们的官方Redux工具包包,并推断store.dispatch的类型,如下所示:
然后,您可以将改进的Dispatch
类型与usedpatch
挂钩一起使用
(FWIW,重做Redux核心文档“使用TS”页面在我近期的待办事项列表中)这是一个已知的问题,我知道已经解决了,但我不认为它已经发布了?谢谢使用工具箱工作得很好。我不得不重写大部分内容,但它成功了
Possible Unhandled Promise Rejection (id: 0):