React-Router - 链接到同一页面而不触发页面unMount

时间:2017-02-20 12:05:59

标签: javascript reactjs react-router

我正在使用react-router Link来浏览我的SPA应用。

在某些情况下,当从页面到具有相同参数的完全相同页面的链接时,我会遇到这种情况,例如:

我在../page1/2,我有相同路线的链接:

<Link to='/page1/2'>
     click me
</Link>

我的问题是,在这种情况下componentWillUnmountcomponentDidMount没有触发,只有componentDidUpdate

这是有问题的,因为我需要在componentWillUnmount中进行一些清理。

解决方案是什么?

3 个答案:

答案 0 :(得分:4)

您必须检查componentWillReceiveProps以处理此更改,react-router标识组件处于活动状态并且不卸载组件,只需传递新属性即可。

componentWillReceiveProps (nextProps) {
   if(nextProps.id === this.props.id) {
     // Clean component and reload? 
   }
}

答案 1 :(得分:0)

react-router与任何其他组件一样 - 它会触发状态变化。如果州已更改,react的对帐流程将确定哪些组件(在您的情况下,路线)需要重新呈现。

在您的情况下,页面将完全相同,这将使React认为没有发生任何变化。因此,组件永远不会重新渲染,也永远不会卸载。

最简单的解决方案是向onClick添加一个<Link />处理程序,为您进行清理。像这样:

handleCleanup(e) {
  if (window.location.href === e.target.href) {
    // do your cleanup like you do in componentWillUnmount
  }
}
render() { 
  return <Link onClick={this.handleCleanup.bind(this)} to={`/page/1/${this.state.someProp}` />
}

答案 2 :(得分:0)

当你只改变params并渲染相同的处理程序时,处理程序将不会重新加载;它只会被更新,就像React中的孩子不会通过改变他们的道具(除了钥匙)来重新安装。所以你没有得到componentDidMount,而是componentWillReceiveProps。

componentWillReceiveProps (nextProps) {
   // do whatever clean up you need before rerendering
   // goo practise checking somehow that you are in the desired situation
}

无论如何,如果你正在学习这个框架,我建议你看一下真正重要的React Component lifecycle