typescript - Dispatch 不使用 redux-thunk 和 typescript 返回 promise

标签 typescript redux redux-thunk

我实际上正在将一些代码迁移到 typescript ,所以我是所有这些类型的新手。当我将 redux-thunk 与常规 javascript 一起使用时,dispatch 方法返回了一个帮助我处理错误和东西的 promise 。 Action 是这个:

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 Hook 正常调用:

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 中的类型的部分,但我找不到正确的方法来声明此分派(dispatch)函数在我需要时工作。

https://redux.js.org/recipes/usage-with-typescript

更糟糕的是,我在执行操作后收到此运行时错误:

Possible Unhandled Promise Rejection (id: 0):

所以 promise 就在某处。

最佳答案

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

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

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

然后,您可以通过 useDispatch Hook 使用改进的 Dispatch 类型。

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

关于typescript - Dispatch 不使用 redux-thunk 和 typescript 返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66486348/

相关文章:

typescript - TypeScript const 断言和声明之间有什么区别?

javascript - node/nodemon 中的 typescript 是否有源映射支持?

typescript - 从 Redux Toolkit 的 createSlice 获取 Action 类型

reactjs - 何时使用 Redux-saga/Redux thunk,何时不使用?

reactjs - Redux 工具包根据 api 响应更新状态

javascript - redux 异步与 redux thunk 不适用于@connect

angular - 检索事件组件和路径

javascript - 如何分离相互依赖的 redux reducer?

javascript - 如何在 react/redux 中调用 API 并从另一个 child 更新一个 child

javascript - react 路由器,redux, Electron : router isn't rendering