2016-12-30 4 views
0
다음

원산지 코드 :축삭 결과를 먼저 얻은 다음 조치를 보내려면 어떻게해야합니까?

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, 
       }); 
     }); 
    } 
} 

나는
(I 모두 같은 API를 호출 많은 작업을해야하기 때문에) 내가 먼저 API를 결과를 얻을, 그리고 내가하고 싶은 것을 다음 단계를 결정입니다 원하는 내 논리는 다음과 같습니다,하지만 난 그게
당신이 당신의 Axios의 콜백에서 someActionotherAction를 전달할 수없는 이유를 잘 모르겠어요

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

나에게 도와주세요 작동하게하는 방법을 모르겠어요. 왜이게 너를 위해 일하지 않니? 당신이 다른 곳에서 API 호출 함수를 정의하려면

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

, 당신은이 작업을 수행 할 수 있습니다 : 그것은 전달

// 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