【问题标题】:react-router-dom refresh component when route changes路由更改时的react-router-dom刷新组件
【发布时间】:2018-03-05 13:16:56
【问题描述】:

我为不同的路线使用了相同的组件。当路由改变时,我希望组件被渲染。

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

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

什么是很酷的方法?

【问题讨论】:

  • 其中一种方式:&lt;Route path="/hotels" component={props =&gt; &lt;HotelsPage {...props} /&gt;} /&gt;
  • 组件不会刷新,除非它的道具发生变化。您需要将道具显式传递给组件。
  • 谢谢大家。它解决了这个问题。但是,路线更改时如何滚动屏幕顶部? :)
  • 你的意思是一旦你的路线改变了你想滚动到顶部?如果确实解决了您上面提到的问题,我已将其发布为答案,请接受答案:)
  • 是的,没关系。我自己解决了。谢谢!

标签: javascript reactjs react-router


【解决方案1】:

你可以得到这个排序的方法之一是明确地传递道具,比如:

&lt;Route path="/hotels" component={props =&gt; &lt;HotelsPage {...props} /&gt;} /&gt;

【讨论】:

  • 好吧,虽然这解决了最初的问题,但它会在 redux prop 更改时刷新组件。我希望它仅在路线更改时刷新。你有什么想法吗?
  • 没有看到代码不可能告诉你正确的解决方案,上面的解决方案是根据你上面的问题(没有显示redux的迹象)
【解决方案2】:

首先你可以将 Route 聚合成一个类似

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

其次,您的HotelsPage 组件同时在/hotels、/apartments 上呈现,类似于路径参数的情况,其中组件不会在路径更改时再次挂载,而是更新从而调用componentWillReceiveProps生命周期函数,

你可以做的是实现componentWillReceivePropslike

componentWillReceiveProps(nextProps) {
    if (nextProps.location.pathname !== this.props.location.pathname) {
      console.log("here");
      //take action here
    }
  }

DEMO

【讨论】:

  • 是的,你能描述一下“动作”吗?我可以在没有部分状态或道具的情况下重新加载整个组件吗?
  • 重新加载整个组件是什么意思
  • 就像刷新浏览器时一样。
  • 这是迄今为止最好的方法,因为您可以在页面组件内重新渲染组件,从而不会再次加载整个页面组件。
猜你喜欢
  • 2019-04-28
  • 2019-06-04
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多