路由更改时,react-router-dom刷新组件

问题描述 投票:2回答:2

我在不同的路线上使用相同的组件。当路由改变时,我想要渲染组件。

<Switch>
    <Route exact path="/" component={HomePage} />
    <Route path="/hotels" component={HotelsPage} />
    <Route path="/apartments" component={HotelsPage} />
</Switch>

当我将路径路径从/hotels更改为/apartments时,组件HotelsPage不会刷新。

对此有什么好处?

javascript reactjs react-router
2个回答
3
投票

您可以通过明确传递道具的方式之一:

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


2
投票

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

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.