javascript - 如何检查反应组件是否分离
问题描述
有一个问题,如何检查反应组件是否与其父组件分离?
假设我有一个反应组件,它订阅了任何异步事件:WebSocket、计时器。
我只是不想在不再使用反应组件时将计算机资源浪费在侦听此事件上,并且也取消分配反应组件。
有吗?
解决方案
React 提供了各种方法来跟踪组件的生命周期。在您的情况下,您需要跟踪组件是否已卸载。因此,根据您使用的组件类型,有两种方法:
类组件
使用componentUnmount生命周期方法。
class YourComponent extends Component {
constructor(props) {
super(props);
}
componentWillUnmount() {
// this method is invoked immediately before a component
// is unmounted and destroyed. you can perform any necessary
// cleanup in this method, such as invalidating
// timers, canceling network requests,
// or cleaning up subscriptions
}
render() {
return (
<div>
{/* ...contents... */}
</div>
);
}
}
功能组件
const YourComponent = () => {
useEffect(() => {
// rest of code
return () => {
// similar to componentWillUnmount() method, this function
// would invoke at the time of component's unmount.
};
},[]);
return (
<div>
{/* ...contents... */}
</div>
);
}
推荐阅读
- google-cloud-platform - 为什么 gcb 中的历史不能按分支名排序?
- sql - 在 SQL 中,将不同的数据类型指定给外键而不是它引用的主键是否是语法错误?
- linux - 在`perf record`的输出上运行`perf stat`?
- javascript - html多个
- 在一页上以不同的开头列出
- python-3.x - 为什么 python os 仅适用于默认目录以及如何更改它?
- jdbc - 不推荐使用构造“jdbc:Client”。选择?
- laravel - Laravel Collection 与 groupby、count 和 sum
- javascript - Javascript null 检查性能(比较 if 和 try/catch)
- angular - ion-button 不触发方法
- reactjs - create-react-app 的“--script-version”命令行选项到底是什么?