当url在redux-react中更改时更新状态

时间:2016-06-09 10:02:20

标签: reactjs redux

我有一个显示用户个人资料的Profile组件。在路由更改为user/:userId后,userId查询参数将在ownProps中更新,感谢react-router-redux,然后将其传递到我的演示文稿组件中:

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 个答案:

答案 0 :(得分:1)

您还需要从组件的this.props.fetchProfile方法中调用componentDidUpdate,并进行(可选)附加检查以查看userId是否实际发生了更改。更好的是,你应该在一个单独的方法中包含fetchProfile的调用,以防万一你想要在userId为空时跳过调用。

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

componentDidMount() {
  this.fetchProfile()
}

componentDidUpdate (prevProps) {
  prevProps.userId !== this.props.userId && this.fetchProfile()
}
相关问题