2016-06-09 84 views
1

我有一个显示用户配置文件的Profile组件。在路线改变user/:userIduserId查询参数将在ownProps由于更新到react-router-redux和将被传递到我的演示组件:URL更改时的更新状态还原反应

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

在这一点上,我需要从userId获取用户配置文件。我应该在哪里抓取?目前,我在componentDidMount

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

做它的这种方法的缺点是,如果用户从去到/users/1/users/2componentDidMount不会触发。这应该怎么做?

回答

1

您还需要从组件的componentDidUpdate方法中调用this.props.fetchProfile,并用(可选)附加检查来查看userId是否实际更改。更好的是,例如,如果userId为空,那么您应该使用单独的方法将fetchProfile的呼叫包装起来,以防万一您想跳过呼叫。

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

componentDidMount() { 
    this.fetchProfile() 
} 

componentDidUpdate (prevProps) { 
    prevProps.userId !== this.props.userId && this.fetchProfile() 
}