我怎样才能先得到 axios 结果,然后发送动作?

How can I get axios result first ,then send action ?

这是原始代码:

export function startGame() {
    return function(dispatch) {
        axios({
          method: 'post',
          url: '/api/actions/game/',
          data: {'game':'start'},
          headers: getHeaders(),
        })
        .then(response => {
          if(response.status===200){
            dispatch({
              type: TYPE.START_GAME,
            });
          }
        })
        .catch((error) => {
            dispatch({
                  type: TYPE.ERROR,
                });
        });
    }
}

我想要的是先得到 api 结果,然后决定下一步我想做什么(因为我有很多动作都调用相同的 api )
我的逻辑如下,但我不知道如何让它工作
请帮助我

export function startGame() {


    let result =  function(dispatch) {
        axios({
          method: 'post',
          url: '/api/actions/game/',
          data: {'game':'start'},
          headers: getHeaders(),
        })
        .then(response => {
          if(response.status===200){
            return {
                "result" : "OK",
                "data" : response.data
            }
          }
        })
        .catch((error) => {
            return {
                "result" : "FAIL",
                "data" : error
            }
        });
    }


    if result.result === "OK" {
        dispatch(someAction())
    }else{
        dispatch(otherAction())
    }


}

我不确定为什么不能在 axios 回调中发送 someActionotherAction。为什么这对你不起作用?

export function startGame() {
      return function(dispatch) {
        axios({
          method: 'post',
          url: '/api/actions/game/',
          data: {'game':'start'},
          headers: getHeaders(),
        })
        .then(response => {
          if (response.status === 200) {
            dispatch(someAction(response.data));
          }
        })
        .catch((error) => {
            dispatch(otherAction(error));
        });
    }
}

如果你想在别处定义API调用函数,你可以这样做:

// In some other file, say api.js
export function startGameApiCall() {
  return axios({
    method: 'post',
    url: '/api/actions/game/',
    data: {'game':'start'},
    headers: getHeaders(),
  });
}

// In your actions file
import { startGameApiCall } from './api';

export function startGame() {
  return function (dispatch) {
    startGameApiCall()
      .then(response => dispatch(someAction(response.data)))
      .catch(() => dispatch(otherAction()));
  }
}

我也会研究 https://github.com/svrcekmichal/redux-axios-middleware 它会根据您的 axios 请求的结果调度另一个操作。