2016-10-18 2 views
0

그래서 지난 이틀 동안이 문제에 곤란을 겪었습니다.Redux Thunk - 약속이있는 비동기 체인 작업

그래서 앱에는 여러 조직이 있습니다. 또한 사용자가 조직간에 전환 할 수있는 조치가 있습니다.

조직 감속기가 :

import { 
    FETCH_ORGANIZATION_LIST_REQUEST, 
    FETCH_ORGANIZATION_LIST_SUCCESS, 
    ORGANIZATION_ERROR, 
    PICK_ORGANIZATION } from '../actions/types' 

const INITIAL_STATE = { error: null, organizations: [], isFetching: false, currentOrganization: null, hasCurrentOrganization: false }; 

export default function (state = INITIAL_STATE, action) { 
    switch (action.type){ 
     case FETCH_ORGANIZATION_LIST_REQUEST: 
      return { ...state, isFetching: action.isFetching, error: null}; 
     case FETCH_ORGANIZATION_LIST_SUCCESS: 
      return { ...state, isFetching: action.isFetching, organizations: action.payload, error: null }; 
     case ORGANIZATION_ERROR: 
      return { ...state, isFetching: action.isFetching, error: action.payload }; 
     case PICK_ORGANIZATION: 
      return { ...state, currentOrganization: action.organizationId, hasCurrentOrganization: action.hasCurrentOrganization }; 
     default: 
      return state 
    } 
} 

조직을 취득 해 조직 통화를 선택하면 다음과 같습니다 : 나는 또한 다른 서버 호출에 사용되는 GetData의 호출을 가지고

export function fetchOrganizationList() { 
    const url = `/organizations`; 

    return (dispatch) => getData(
     FETCH_ORGANIZATION_LIST_REQUEST, 
     FETCH_ORGANIZATION_LIST_SUCCESS, 
     ORGANIZATION_ERROR, 
     true, 
     url, 
     dispatch); 
}; 

export function pickOrganization(organizationId) { 
    return (dispatch) => { 
     dispatch({ 
      type: PICK_ORGANIZATION, 
      organizationId: organizationId, 
      hasCurrentOrganization: true 
     }) 
    } 
}; 

:

그리고 마지막으로 OrganizationSelector.jsx 컨테이너 구성 요소가 있습니다. 현재 조직을 고르고 선택하겠습니다.

import React, { 
    Component, 
    PropTypes, 
} from 'react'; 
import { connect } from 'react-redux'; 
import { bindActionCreators } from 'redux'; 

import { fetchOrganizationList, pickOrganization, fetchAndPickCurrentOrganization } from '../../actions/organizations'; 

import Picker from '../../components/Picker'; 

class OrganizationSelector extends Component { 


    componentDidMount() { 

     this.props.fetchOrganizationList(); 
    } 

    render() { 
     const { isFetching, error, organizations, dispatch } = this.props; 

     let count = !isFetching ? organizations.count : 1; 

     return (
      <div> 
       {isFetching && !error && 
       <li>Loading...</li>} 
       {!isFetching && !error && count > 1 && 
       <Picker 
        currentOrganization={organizations.results[0].name} 

        options={organizations.results} 
        onSubmit={pickOrganization()} 
       /> 
       } 
       {!isFetching && !error && count === 1 && 
       <div> 
        {organizations.results[0].name} 
       </div> 
       } 
      </div> 
     ); 
    } 
} 

OrganizationSelector.propTypes = {}; 
OrganizationSelector.defaultProps = {}; 

const mapStateToProps = state => ({ 
    organizations: state.organization.organizations, 
    isFetching: state.organization.isFetching, 
    error: state.organization.error 
}); 

function mapDispatchToProps(dispatch) { 
    return { 
     fetchOrganizationList: bindActionCreators(fetchOrganizationList, dispatch), 
     // pickOrganization: bindActionCreators(pickOrganization, dispatch) 
    } 
} 

export default connect(mapStateToProps, mapDispatchToProps)(OrganizationSelector); 

는 지금은 fetchListAndPickCurrentOrganization을함으로써 creator.I가 fetchOrganizationList 액션, 나는 여러 가지 일을 시도 가져 오는 완료 후 picOrganization 조치를 전달하려는 동일한 작업에서 함께 작업을 체인되는 문제가 무엇입니까 곳() 함수를 호출합니다.

export function fetchListAndPickCurrentOrganization() { 
    return (dispatch) => { 
     dispatch(fetchOrganizationList()) 
      .then(response => { 
       console.log(response) // This is where the Pick organization call will go 
      }) 
      .catch(() => { 
       console.log('error') 
      }) 
    } 
}; 

은 또한 직접 fetchOrganizationList() 호출에서 Axios의 호출을 시도,하지만 난이 Axios의 호출에서 반환 된 응답을 전달 받고되지 않기 때문에 추측하고있어, 이는 정의되지 않은 그 때는 점점 계속 ~을 통해.

여러 가지를 시도했지만 목표는 앱을 처음 설치할 때이 두 가지 호출을 실행하는 것입니다. pickOrganization 호출은 물론 조직간에 전환하는 데 다시 사용됩니다.

+1

'getData'에서'axios.get (...)'호출을 시도해 보셨습니까? 이 약속이 없으면 약속은 공개되지 않으므로 작업을 보낸 후'.then (...) '을 호출 할 수 없습니다. –

+0

그렇기 때문에 호출을 연결하는 것은 마치'axios.get (...), then (...), then (...)' – md85

+0

처럼 작동합니다. 그러나 일반적으로 코드를 가능한. Redux thunk와 함께 작업하기가 더 쉬우면 Fetch로 전환하는 것이 가능합니다. 편집 : 아, 나는 당신이 무슨 뜻인지 안다, 아니, 나는 그 일을 시도하지 않은 시도하지 않았습니다. – md85

답변

0

그래서 솔루션은 매우 간단했습니다. 나는 axios.get 요청을 반환해야했습니다. 초기 솔루션에서 반환되지 않았기 때문에 아무것도 전달되지 않았습니다. 그리고 정의되지 않았습니다.

export function getData(actionRequest, actionSuccess, errorType, isAuthReq, url, dispatch) { 
    const requestUrl = API_URL + url; 
    let headers = {}; 

    dispatch({ 
     type: actionRequest, 
     isFetching: true, 
     error: null 
    }); 

    if(isAuthReq) { 
     headers = {headers: {'Authorization': 'Token ' + cookie.load('token')} } 
    } 

    return axios.get(requestUrl, headers) 
     .then((response) => { 
      dispatch({ 
       type: actionSuccess, 
       isFetching: false, 
       payload: response.data 
      }); 
      return response.data; 
     }) 
     .catch((error) => { 
      errorHandler(dispatch, error, errorType) 
     }) 

} 

나를 위해이를 해결하기 위해 당신에게 @Ashley 'CptLemming'윌슨 감사드립니다.

관련 문제