同时更新路由和redux状态数据

时间:2017-04-22 22:00:38

标签: reactjs

我有一个拥有用户个人资料的应用。在用户个人资料中有一个朋友列表,当点击朋友时,它会带你到其他用户个人资料。

目前,当我点击导航到另一个配置文件(通过redux-router链接)时,它会更新URL,但不会更新配置文件或呈现新路由。

这是一个简化的代码段,为简单起见,我已经删除了很多代码。下面还有一些层,但问题发生在我的配置文件容器的顶层。如果我可以让userId prop更新为ProfileSections,那么一切都会传播。

class Profile extends Component {

  componentWillMount() {
    const { userId } = this.props.params

    if (userId) { this.props.getUser(userId) }
  }

  render() {
    return <ProfileSections userId={user.id} />
  }
}

const mapStateToProps = ({ user }) => {
  return { user }
}

export default connect(mapStateToProps, { getUser })(Profile);

正如您所看到的,发生的情况是我在getUser上运行componentWillMount操作,这只会发生一次,这是路由更改但配置文件数据不会更新的原因。< / p>

当我将其更改为另一个生命周期钩子(如componentWillUpdate)以运行getUser操作时,我会进入无限循环的请求,因为它会不断更新状态然后更新组件。

我还尝试使用在路由组件上的react-router提供的onEnter挂钩,但是当从一个配置文件导航到另一个配置文件时它不会触发,因为它是相同的路由,所以不会工作。

我相信我是以错误的方式思考这个问题,而且正在寻找一些指导,说明如何处理从一个配置文件导航到另一个配置文件的情况,同时将数据存储在redux存储中。

1 个答案:

答案 0 :(得分:0)

所以我建议你通过以下方式解决这个问题:

class Profile extends Component {
  componentWillMount() {
    const { userId } = this.props.params

    if (userId) { 
      // This is the initial fetch for your first user.
      this.fetchUserData(userId)
    }
  }

  componentWillReceiveProps(nextProps) {
    const { userId } = this.props.params
    const { userId: nextUserId } = nextProps.params

    if (nextUserId && nextUserId !== userId) {
      // This will refetch if the user ID changes.
      this.fetchUserData(nextUserId)
    }
  }

  fetchUserData(userId) {
    this.props.getUser(userId) 
  }

  render() {
    const { user } = this.props

    return <ProfileSections userId={user.id} />
  }
}

const mapStateToProps = ({ user }) => {
  return { user }
}

export default connect(mapStateToProps, { getUser })(Profile);

请注意,我已将其设置为componentWillMount生命周期方法,您可以请求初始userIdcomponentWillReceiveProps方法中的代码检查是否已收到新用户ID(导航到其他配置文件时会发生这种情况),如果是,则重新获取数据。

您可以考虑分别使用componentDidMountcomponentDidUpdate代替componentWillMountcomponentWillReceiveProps fetchUserData来电,但这可能取决于您的使用案例。