【问题标题】:Dispatch is not returning a promise using redux-thunk with typescriptDispatch 没有使用带有 typescript 的 redux-thunk 返回承诺
【发布时间】:2021-06-03 18:26:23
【问题描述】:

我实际上正在将一些代码迁移到打字稿,所以我对所有这些类型的东西都是新手。当我将 redux-thunk 与常规 javascript 一起使用时,dispatch 方法返回了一个可以帮助我处理错误和东西的承诺。行动是这样的:

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};
        }
    }
}

这执行没有问题,但如果我尝试处理这个:

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):

所以承诺就在某个地方。

【问题讨论】:

标签: typescript redux redux-thunk


【解决方案1】:

基本的Dispatch 类型不知道thunk。你需要推断出 store.dispatch 的修改类型,它告诉 TS thunk 是可以接受的,然后它就会明白调度 thunk 实际上会返回一个 Promise。

这里最好的选择是切换到使用我们的官方 Redux Toolkit 包,并推断 store.dispatch 的类型,如下所示:

https://redux-toolkit.js.org/tutorials/typescript

然后,您可以将改进后的 Dispatch 类型与 useDispatch 挂钩使用。

(FWIW,重做 Redux 核心文档“使用 TS”页面在我近期的待办事项列表中)

【讨论】:

  • 谢谢.. 使用工具包效果很好。我不得不重写大部分,但它完成了工作
猜你喜欢
  • 1970-01-01
  • 2018-12-28
  • 2017-01-20
  • 2019-11-14
  • 2019-07-15
  • 1970-01-01
  • 2019-01-27
  • 2016-11-14
  • 2020-04-30
相关资源
最近更新 更多