我在不同的路线上使用相同的组件。当路由改变时,我想要渲染组件。
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/hotels" component={HotelsPage} />
<Route path="/apartments" component={HotelsPage} />
</Switch>
当我将路径路径从/hotels
更改为/apartments
时,组件HotelsPage
不会刷新。
对此有什么好处?
您可以通过明确传递道具的方式之一:
<Route path="/hotels" component={props => <HotelsPage {...props} />} />
首先,您可以将Route聚合成一个类似的
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/(hotels|apartments)" component={HotelsPage} />
</Switch>
第二,你的HotelsPage
组件在/hotels
,/apartments
上呈现,它类似于路径参数,因此组件不会在路径更改时再次装载,但更新因此调用componentWillReceiveProps
生命周期函数,
你能做的就是实现componentWillReceiveProps
之类的
componentWillReceiveProps(nextProps) {
if (nextProps.location.pathname !== this.props.location.pathname) {
console.log("here");
//take action here
}
}