javascript 当路由改变时react-router-dom刷新组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49111353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
react-router-dom refresh component when route changes
提问by Leo
I used same component for different routes. When route changes, I want the component to be rendered.
我为不同的路线使用了相同的组件。当路由改变时,我希望组件被渲染。
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/hotels" component={HotelsPage} />
<Route path="/apartments" component={HotelsPage} />
</Switch>
When I change the route path from /hotelsto /apartments, the component HotelsPagedoesn't refresh.
当我将路由路径从 更改/hotels为 时/apartments,组件HotelsPage不会刷新。
What is the cool approach for this?
什么是很酷的方法?
回答by Aaqib
One of the ways you can get this sorted is by passing the props explicitly like :
您可以通过以下方式进行排序的方法之一是显式传递道具:
<Route path="/hotels" component={props => <HotelsPage {...props} />} />
<Route path="/hotels" component={props => <HotelsPage {...props} />} />
回答by Shubham Khatri
Firstly you can aggregate the Route into one like
首先,您可以将 Route 聚合为一个
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/(hotels|apartments)" component={HotelsPage} />
</Switch>
and secondly, your HotelsPagecomponent is rendered both on /hotels, /apartments, it is similar case like path params, whereby the component doesn't mount again on path change, but updates thereby calling componentWillReceivePropslifecycle function,
其次,您的HotelsPage组件在/hotels,上都呈现/apartments,这与路径参数类似,即组件不会在路径更改时再次挂载,而是更新从而调用componentWillReceiveProps生命周期函数,
What you can do is implement componentWillReceivePropslike
你可以做的是实现componentWillReceiveProps像
componentWillReceiveProps(nextProps) {
if (nextProps.location.pathname !== this.props.location.pathname) {
console.log("here");
//take action here
}
}

