首页 > 解决方案 > 如何检查反应组件是否分离

问题描述

有一个问题,如何检查反应组件是否与其父组件分离?

假设我有一个反应组件,它订阅了任何异步事件:WebSocket、计时器。

我只是不想在不再使用反应组件时将计算机资源浪费在侦听此事件上,并且也取消分配反应组件。

有吗?

标签: javascriptreactjslistener

解决方案


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>
    );
  }
}

功能组件

将useEffect钩子与cleanup结合使用。

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>
  );
}

推荐阅读