【问题标题】:How can I get axios result first ,then send action ?如何先获取 axios 结果,然后发送操作?
【发布时间】:2016-12-30 06:38:48
【问题描述】:

这里是源代码:

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


}

【问题讨论】:

    标签: redux redux-thunk axios


    【解决方案1】:

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

    【讨论】:

    • 非常感谢,这就是我想要的
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-02-04
      • 2015-10-12
      • 1970-01-01
      • 2016-01-23
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多