实际上,我正在将一些代码迁移到类型记录中,所以我在所有这些类型的内容中都是新手。当我在普通javascript中使用redux-thunk时,调度方法返回了一个帮助我处理错误和其他事情的承诺。行动是这样的:
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));现在我已经将代码迁移到了类型记录,下面的操作如下所示:
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};
}
}
}这是没有问题地执行的,但是如果我试图处理这个问题:
dispatch(login({username: "admin", password: "adminpassword1"}))
.then(d => console.log("ok"))
.catch(err => console.log(err));我知道这个错误:
TS2339: Property 'then' does not exist on type 'ThunkAction >, {}, {}, AnyAction>'我试着阅读关于Redux中类型的部分,但是我找不到正确的方法来声明这个分派函数,因为我需要它。
https://redux.js.org/recipes/usage-with-typescript
更糟糕的是,在执行操作之后,我将得到这个运行时错误:
Possible Unhandled Promise Rejection (id: 0):所以承诺就在某个地方。
发布于 2021-03-06 02:12:48
基本的Dispatch类型不知道块。您需要推断修改过的store.dispatch类型,它告诉TS块是可以接受的,然后它就会理解分派thunk实际上返回了一个承诺。
这里最好的选择是切换到使用我们的官方Redux包,并推断出store.dispatch的类型,如下所示:
https://redux-toolkit.js.org/tutorials/typescript
然后,可以将改进的Dispatch类型与useDispatch挂钩一起使用。
(FWIW,重做Redux核心文档“与TS一起使用”页面在我的待办事项清单上,为不久的将来)
https://stackoverflow.com/questions/66486348
复制相似问题