Leo*_*Leo 4 javascript reactjs react-router
我为不同的路线使用了相同的组件。当路由改变时,我希望组件被渲染。
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/hotels" component={HotelsPage} />
<Route path="/apartments" component={HotelsPage} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
当我将路由路径从 更改/hotels为 时/apartments,组件HotelsPage不会刷新。
什么是很酷的方法?
您可以通过以下方式进行排序的方法之一是显式传递道具:
<Route path="/hotels" component={props => <HotelsPage {...props} />} />
首先,您可以将 Route 聚合为一个
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/(hotels|apartments)" component={HotelsPage} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
其次,您的HotelsPage组件在/hotels,上都呈现/apartments,这与路径参数类似,即组件不会在路径更改时再次挂载,而是更新从而调用componentWillReceiveProps生命周期函数,
你可以做的就是实现componentWillReceiveProps像
componentWillReceiveProps(nextProps) {
if (nextProps.location.pathname !== this.props.location.pathname) {
console.log("here");
//take action here
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18456 次 |
| 最近记录: |