Dispatch 不使用 redux-thunk 和打字稿返回承诺

Dispatch is not returning a promise using redux-thunk with typescript

我实际上正在将一些代码迁移到打字稿,所以我是所有这些类型的新手。当我使用带有常规 javascript 的 redux-thunk 时,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):

所以承诺就在某处。

基本 Dispatch 类型不知道 thunk。您需要推断 store.dispatch 的修改类型,告诉 TS thunk 是可以接受的,然后它会理解调度 thunk 实际上 returns 一个承诺。

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

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

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

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