may*_*aah 2 reactjs react-router react-router-dom
我注意到当我在 /users/:id1 链接上尝试访问新的用户个人资料页面 /users/:id2 时,它不会重新加载我正在尝试访问的新用户 ID 的数据,但是如果我来自 /forums 或 /search 等不同的页面,它会正常加载
我已经试过了,componentWillReceiveProps但我不确定我是否正确地实施了它,也不知道现在使用 b/c 是否安全它现在可能会被弃用???
我也试过用 withRouter 包装我的 UserProfile 但似乎更糟,因为当我刷新页面时没有数据加载
应用程序.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>
Run Code Online (Sandbox Code Playgroud)
我的链接的样子
<Link className="pt-button pt-minimal" to={"/user/"+this.props.currentUserId}>My Profile</Link>
Run Code Online (Sandbox Code Playgroud)
我对 componentWillReceiveProps 的尝试
if (nextProps.match.params.id !== this.props.match.params.id) {
this.setState({
userId: nextProps.match.params.id,
})
this.componentWillMount();
}
Run Code Online (Sandbox Code Playgroud)
预期:当单击指向另一个用户配置文件的链接时,它会使用该新用户配置文件的数据重定向到新用户配置文件
实际:url 更改但没有数据重新加载。
我认为您非常接近,但是对生命周期方法以及何时/如何调用它们的误解会导致一些问题。
您可能应该使用componentDidUpdate. 我也会避免将道具存储在 state 中,因为它们需要保持同步。
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 });
})
}
}
Run Code Online (Sandbox Code Playgroud)
另外,不要手动触发生命周期方法(如评论中所述)
| 归档时间: |
|
| 查看次数: |
1993 次 |
| 最近记录: |