2016-06-09 2 views
1

사용자 프로필을 표시하는 Profile 구성 요소가 있습니다. user/:userId 노선 변화에서 userId 쿼리 PARAM은 react-router-reduxownProps 덕분에 업데이트됩니다 다음 프레젠테이션의 구성 요소에 전달됩니다 :이 시점에서redux-react에서 url이 변경 될 때 업데이트 상태가

const mapStateToProps = (state, ownProps) => ({ 
    userId: ownProps.params.userId, 
    user: store.profile.user //null at first, will be updated later 
}) 

, 나는 userId에서 사용자 프로필을 가져올 필요가있다. 이 가져 오기는 어디에서해야합니까? 사용자가 /users/1에서 /users/2, componentDidMount 습관 트리거로 이동하면 현재 내가 componentDidMount

componentDidMount() { 
    this.props.fetchProfile(this.props.userId) //this will dispatch an action to fetch user details and store in `store.profile.user` 
} 

이의 단점을 그 일을하고 같습니다. 어떻게해야합니까?

답변

1

구성 요소의 componentDidUpdate 메서드에서 this.props.fetchProfile 메서드를 호출하고 (선택 사항) 추가 확인을 사용하여 userId이 실제로 변경되었는지 확인해야합니다. 더 나은 것은 fetchProfile의 전화를 별도의 방법으로 랩핑해야합니다. 예를 들어 userId이 null 인 경우 전화를 건너 뛰려는 경우에 대비해야합니다.

fetchProfile() { 
    this.props.userId && this.props.fetchProfile(this.props.userId) 
} 

componentDidMount() { 
    this.fetchProfile() 
} 

componentDidUpdate (prevProps) { 
    prevProps.userId !== this.props.userId && this.fetchProfile() 
} 
관련 문제