我正在使用react-router Link
浏览我的SPA应用程序。
在某些情况下,我会遇到这样的情况:从一个页面到具有相同参数的完全相同的页面的链接,例如:
我在../page1/2
,并且我有一个指向相同路由的链接:
<Link to='/page1/2'>
click me
</Link>
我的问题是,在这种情况下,componentWillUnmount
和componentDidMount
不会触发,只会触发componentDidUpdate
。
这是有问题的,因为我需要在componentWillUnmount
中进行一些清理。
解决方案是什么?
发布于 2017-02-20 20:32:45
您必须检查componentWillReceiveProps以处理此更改,react-router标识组件是活动的,并且不卸载组件,只是传递新的属性。
componentWillReceiveProps (nextProps) {
if(nextProps.id === this.props.id) {
// Clean component and reload?
}
}
发布于 2017-02-20 20:33:58
react-router
的工作原理和其他组件一样--它触发状态的改变。如果状态发生了变化,react
的协调过程将找出哪些组件(在您的示例中是路由)将需要重新呈现。
在您的情况下,页面将是完全相同的,这将使React认为没有发生任何更改。因此,组件永远不会重新呈现,也永远不会卸载。
最简单的解决方案是向为您执行清理的<Link />
添加一个onClick
处理程序。如下所示:
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}` />
}
发布于 2017-02-20 20:37:27
当你只改变参数并且呈现相同的处理程序时,处理程序不会重新挂载;它只会被更新,就像React中的孩子不会通过改变他们的道具(key除外)来重新挂载一样。你得到的不是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,这是非常重要的。
https://stackoverflow.com/questions/42344163
复制相似问题