当路由改变时react-router-dom刷新组件

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不会刷新。

什么是很酷的方法?

Aaq*_*qib 7

您可以通过以下方式进行排序的方法之一是显式传递道具:

<Route path="/hotels" component={props => <HotelsPage {...props} />} />


Shu*_*tri 5

首先,您可以将 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)

演示