Reactjs 同时更新路由和重发状态数据

Reactjs 同时更新路由和重发状态数据,reactjs,Reactjs,我有一个具有用户配置文件的应用程序。在用户配置文件上有一个朋友列表,当单击一个朋友时,它会将您带到另一个用户配置文件 当前,当我单击导航到其他配置文件(通过redux路由器链接)时,它会更新URL,但不会更新配置文件或呈现新路由 这是一个简化的代码片段,为了简单起见,我已经删除了很多代码。下面还有一些层,但问题发生在我的配置文件容器的顶层。如果我可以为ProfileSections更新userId道具,那么一切都将通过它传播 class Profile extends Component {

我有一个具有用户配置文件的应用程序。在用户配置文件上有一个朋友列表,当单击一个朋友时,它会将您带到另一个用户配置文件

当前,当我单击导航到其他配置文件(通过redux路由器链接)时,它会更新URL,但不会更新配置文件或呈现新路由

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

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);
类配置文件扩展组件{
组件willmount(){
const{userId}=this.props.params
if(userId){this.props.getUser(userId)}
}
render(){
返回
}
}
常量mapStateToProps=({user})=>{
返回{user}
}
导出默认连接(mapstatetops,{getUser})(配置文件);
如您所见,发生的情况是,我正在
组件willmount
上运行
getUser
操作,这只会发生一次,这也是路由更改但配置文件数据不更新的原因

当我将其更改为另一个生命周期钩子(如
componentWillUpdate
)来运行getUser操作时,我会收到无数的请求,因为它会不断更新状态,然后更新组件

我也尝试过使用react router on Route组件提供的
oneter
钩子,但它在从一个配置文件导航到另一个配置文件时不会触发,因为它是同一个路由,所以无法工作


我认为我的想法是错误的,我正在寻找一些关于如何处理在数据存储在redux store中时从一个配置文件导航到另一个配置文件的指导。

因此我建议您采用以下方法:

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);
类配置文件扩展组件{
组件willmount(){
const{userId}=this.props.params
if(userId){
//这是第一个用户的初始获取。
this.fetchUserData(userId)
}
}
组件将接收道具(下一步){
const{userId}=this.props.params
const{userId:nextUserId}=nextProps.params
if(nextUserId&&nextUserId!==userId){
//如果用户ID更改,将重新蚀刻。
this.fetchUserData(nextUserId)
}
}
fetchUserData(用户ID){
this.props.getUser(userId)
}
render(){
const{user}=this.props
返回
}
}
常量mapStateToProps=({user})=>{
返回{user}
}
导出默认连接(mapstatetops,{getUser})(配置文件);
请注意,我已经设置了它,因此在
组件willmount
生命周期方法中,您可以请求初始
用户ID
组件willreceiveprops
方法中的代码检查是否收到了新的用户ID(当您导航到其他配置文件时会发生这种情况),如果收到,则重新获取数据

您可以考虑使用<代码>组件>组件-Debug更新< /COD>而不是<代码>组件> />代码>和<>代码>组件将分别接收代码<> FutcUsReDATAs/<代码>调用,但它可以取决于您的用例。

您可以查看它是否适合您的用例。