我注意到当我在/ users /:id1链接上尝试进入新的用户个人资料页面/ users /:id2时,它不会重新加载我要访问的新用户ID的数据,但是如果我来自/ forums或/ search之类的其他页面,它将很好地加载
我已经尝试过了,componentWillReceiveProps
但是我不确定我是否正确实施了它,也不知道使用b / c是否安全,现在可能已弃用了???
我也尝试用withRouter包裹我的UserProfile,但似乎变得更糟,因为刷新页面时不会加载任何数据
App.js
<BrowserRouter onUpdate={() => window.scrollTo(0, 0)} >
<div>
<Switch>
<Route exact path="/search" component={Search}/>
<Route exact path="/forum" component={Forum}/>
<Route exact path="/user/:id" component={UserProfile} currentUserId={this.state.currentUserId}/>
</Switch>
</div>
</BrowserRouter>
我的链接看起来如何
<Link className="pt-button pt-minimal" to={"/user/"+this.props.currentUserId}>My Profile</Link>
我对componentWillReceiveProps的尝试
if (nextProps.match.params.id !== this.props.match.params.id) {
this.setState({
userId: nextProps.match.params.id,
})
this.componentWillMount();
}
预期:单击指向另一个用户配置文件的链接时,它将使用该新用户配置文件的数据重定向到新用户配置文件
实际:网址已更改,但没有重新加载数据。
我认为您已经很接近了,但是错误理解的生命周期方法以及何时/如何调用它们的混合导致了一些问题。
您可能应该使用componentDidUpdate
。我也将避免将道具存储在状态中,因为它们随后需要保持同步。
componentDidUpdate(prevProps) {
if (prevProps.match.params.id !== this.props.match.params.id) {
this.setState({ user: null });
fetchUserData(this.props.match.params.id)
.then((user) => {
this.setState({ user: user });
})
}
}
另外,请勿手动触发生命周期方法(如注释中所述)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句