gpt4 book ai didi

javascript - 如何在路由更改时卸载组件

转载 作者:可可西里 更新时间:2023-11-01 02:20:58 25 4
gpt4 key购买 nike

我在给定路线上有一个组件,比如 app.com/cars/1

我有一个侧边栏,其中包含指向不同汽车的链接,例如 /cars/2/cars/3

我遇到的问题是当您更改链接时,比如从 cars/1cars/2,组件没有卸载,我得到componentWillReceiveProps 已触发。如果我转到另一个包含不同组件的页面,例如 /trucks,该组件已卸载,一切正常。

当路由改变时,如何卸载我的组件?我想要为下一辆车清除各种状态和通量的东西。或者,如果不卸载,人们是否有处理此类问题的典型方式?我无法想象这不是很常见。

(注意我正在使用 react-router)

最佳答案

我认为处理此问题的正常方法是在 componentWillReceiveProps 中注销和重新注册您的监听器、重置您的状态等。围绕此行为创建抽象是正常的:

componentWillMount: function() {
this.setupStuff(this.props);
}

componentWillUnmount: function() {
this.tearDownStuff();
}

componentWillReceiveProps: function(nextProps) {
this.tearDownStuff();
this.setupStuff(nextProps);
}

setupStuff: function(props) {
this.setState(this.getDataFromStore(props.store));
props.store.listen(this.handler); // or whatever
}

tearDownStuff: function(props) {
props.store.unlisten(this.handler); // or whatever
}

但是,如果您真的想重新安装组件,可以使用几个选项。

如果您不希望任何组件在路由更改时保持挂载状态,您可以使用the createElement option。为组件添加唯一 key 的路由器:

function createElement(Component, props) {
var key = ...; // some key that changes across route changes
return <Component key={key} {...props} />;
}

// ...

<Router createElement={createElement}>
...

但是,我不推荐这样做。这不仅会使您的应用变慢,因为每个 路由组件每次都会重新挂载,而且还会完全禁用具有不同 Prop 的同一路由处理程序的后续渲染之间的动画。

如果您只希望某些路由总是重新渲染,您可以通过React.cloneElement在父级中给它一个键:

render: function() {
var key = ...; // some key that changes across route changes
return React.cloneElement(
React.Children.only(this.props.children),
{key: key}
);
}

关于javascript - 如何在路由更改时卸载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32961014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com