首页 > 解决方案 > 在 Axios.post 和调度操作之后,无法在 Redux Thunk 中执行回调

问题描述

我写了一个 redux thunk,以便在向 API 发出 post 请求后,会分派一个动作并执行一个回调:

import actionTypes from '../actions/actionTypes';
import axios from 'axios';

function postThunk(someValue, callback) {
 return dispatch => {
    try {
        let token = localStorage.getItem('token');
        const credentials = {
            headers: {
                "Authorization" : 'Bearer '+ token,
              },
            };
        const data = {
            someValue
        }
        axios.post('http://myAPI',data, credentials).then(result =>{
            dispatch({
                type: actionTypes.MY_ACTION,
                data: result,
            })
        });
        callback();
    } catch (error) {
        console.log(error);
    }
}
}

export{
 postThunk
};

当我调用 thunk 时的回调实际上只是一个this.props.history.push(/somelocation). 所以如上所述它有效,但我实际上希望回调位于 axios.post 承诺链中,因为重定向应该只发生在 POST 请求之后。但是,如果我将代码更改为:

            axios.post('http://myAPI',data, credentials).then(result =>{
            dispatch({
                type: actionTypes.MY_ACTION,
                data: result,
            });
            callback();
        });

不知何故,它不再起作用了。POST 请求正在发生并且数据库得到更新,但不是重定向同一页面而是硬重新加载,这使得调试也非常困难,因为我真的看不到发生了什么。有谁知道我需要照顾什么,是调度抛出错误还是我现在需要一个 redux promise 中间件?

标签: reactjsreact-reduxaxiosredux-thunkredux-promise-middleware

解决方案


推荐阅读