2017-01-06 2 views
0

사용자 및 장소는 각 사용자가 배치 할 수있는 두 개의 서로 다른 데이터베이스로되어 있습니다.데이터를 가져 오는 올바른 방법 - 대답

나는 한 번에 사용자의 한 장소에로드해야하는 구성 요소가 BasicInfo입니다. 내가 하드 코딩하고있어 현재로서는, fetchPlaces에 사용자 ID를 전달해야

componentWillMount() { 
    this.props.dispatch(fetchUser())   
    this.props.dispatch(fetchPlaces(1)) 
} 

BasicInfo

ComponentWillMount,하지만 난 fetchUser의 결과를 어떻게해야합니까? componentWillReceiveProps(nextProps)에서해야합니까? 아니면 다른 방법이 있습니까?

componenetWillReceiveProps은 의미가 있지만 사건의 사슬 인 경우 무엇이 궁금합니다. 다른 데이터를 가져와야하는 경우 장소 ID에 따라 다를 수 있습니다.

작업 :

export function fetchPlaces(user_id) { 
 
    return function(dispatch) { 
 
    axios.get("/getPlaces?user_id=" + user_id) 
 
     .then((response) => { 
 
      console.log(response); 
 
     dispatch({type: "FETCH_PLACES_FULFILLED", payload: response.data}) 
 
     }) 
 
     .catch((err) => { 
 
     dispatch({type: "FETCH_PLACES_REJECTED", payload: err}) 
 
     }) 
 
    } 
 
} 
 

 
export function fetchPlace(place_id) { 
 
    return function(dispatch) { 
 
    axios.get("/getPlace?place_id=" + place_id) 
 
     .then((response) => { 
 
      console.log(response); 
 
     dispatch({type: "FETCH_PLACES_FULFILLED", payload: response.data}) 
 
     }) 
 
     .catch((err) => { 
 
     dispatch({type: "FETCH_PLACES_REJECTED", payload: err}) 
 
     }) 
 
    } 
 
}

답변

1

이미 redux-thunk을 사용하고있는 것 같습니다. (나는 당신의 fetchUseruser이 어떻게 보이는지 추측하고있어) ...

return axios.get(...); 

을 당신은이 같은 작업을 수행 할 수 있습니다 : 그렇다면, 당신은() 호출하여 axios.get에서 약속을 반환 할 수 있습니다

this.props.dispatch(fetchUser()).then(user => this.props.dispatch(fetchPlaces(user.id))) 
+0

감사합니다. Jeff. 따라서 ComponentWillMount에서 데이터를 전달할 방법이 없다고 생각합니다. 소품이 제대로 전달되지 않았기 때문입니다. –

+0

하지만이 경우 사용자, 장소 및 장소를 얻을 때마다? –

+1

소품은 componentWillMount()에서 사용할 수 있습니다. 예를 들어 구성 요소에 "userId"속성이 있으면 this.props.dispatch (fetchUser (this.props.userId) ...)로 전달할 수 있습니다. –

1

당신은 썽크 또는 약속 미들웨어를 사용할 수 있습니다. 동기와 예제는 documentation에서 찾을 수 있습니다.

+0

감사합니다. @R. Haluk –

관련 문제