2017-02-20 45 views
2

我使用react-router Link浏览我的SPA应用程序。React-Router - 链接到同一页面不触发页面unMount

在某些情况下,我得到的情况时,有从页面完全相同的页面的链接使用相同的参数,例如:

我在../page1/2和我有一个链接到相同的路线:

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

我的问题是,在这种情况下componentWillUnmountcomponentDidMount不开火,只有componentDidUpdate

这是有问题的,因为我需要在componentWillUnmount做一些清洁。

解决方案是什么?

+0

这里有两个很好的答案,但从语义上来说,我认为你应该接受@damianfabian的答案。如果您必须根据链接确定的条件重新呈现组件,则添加onClick会更好,但对于您的情况,似乎您希望始终重新呈现它。同样,它们都是正确的,但'componentWillReceiveProps'在语义上更合适。 –

回答

3

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

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

这个工作,用这个解决方案还有一些问题,但是thx – omriman12

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}` /> 
} 
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这是非常重要的,如果你正在学习这个框架。