2016-12-30 87 views
0

這裏是產地代碼:如何首先獲取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()) 
    } 


} 

回答

0

我不知道爲什麼你不能只派遣你的愛可信回調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())); 
    } 
} 
+0

非常感謝你,這是我想要的 – user2492364

相關問題