当路由参数更改时,组件不会重新加载新数据
Component won't reload with new data when route parameters change
我注意到,当我在 /users/:id1 link 上尝试访问新用户个人资料页面 /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 长什么样
<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();
}
预期:当点击 link 到另一个用户个人资料时,它会重定向到具有该新用户个人资料数据的新用户个人资料
实际:url 发生变化但没有数据重新加载。
我认为您非常接近,但是误解生命周期方法和 when/how 它们被调用的混合导致了一些问题。
您可能应该使用 componentDidUpdate
。我也会避免将 prop 存储在 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 });
})
}
}
此外,不要手动触发生命周期方法(如评论中所述)
我注意到,当我在 /users/:id1 link 上尝试访问新用户个人资料页面 /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 长什么样
<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();
}
预期:当点击 link 到另一个用户个人资料时,它会重定向到具有该新用户个人资料数据的新用户个人资料
实际:url 发生变化但没有数据重新加载。
我认为您非常接近,但是误解生命周期方法和 when/how 它们被调用的混合导致了一些问题。
您可能应该使用 componentDidUpdate
。我也会避免将 prop 存储在 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 });
})
}
}
此外,不要手动触发生命周期方法(如评论中所述)