如何首先获得axios结果,然后发送动作?

时间:2016-12-30 06:38:49

标签: redux redux-thunk axios

这是原始代码:

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())
    }


}

2 个答案:

答案 0 :(得分:0)

我不确定为什么你只能在你的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()));
  }
}

答案 1 :(得分:0)

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