Netinfo connectionChange事件侦听器未被分离

时间:2018-01-12 10:30:52

标签: react-native

我在启动画面componentDidMount上添加了connectionChange事件侦听器,但未在componentwillUnmount上删除它。它在应用程序的每个页面上都处于活动状态。如何在componentWillUnmount上分离它。

componentDidMount() {
         NetInfo.addEventListener('connectionChange',
    (networkType)=> {
        this.handleFirstConnectivityChange({networkType})
    }
}

    componentWillUnmount() {
        this.notificationListener.remove();
        NetInfo.removeEventListener(
            'connectionChange'
          );

}

1 个答案:

答案 0 :(得分:1)

您需要将addEventListener中使用的同一回调传递给removeEventListener

class SomeClass extends Component {
  handleConnectivityChange = networkType => {
    //...
  };

  componentDidMount() {
    NetInfo.addEventListener(
      "connectionChange", 
      this.handleConnectivityChange
    );
  }

  componentWillUnmount() {
    NetInfo.removeEventListener(
      "connectionChange", 
      this.handleConnectivityChange
    );
  }
}

请注意,在调用addEventListener时,不应创建新的箭头函数包装器,因为您不会引用该函数实例,并且您可以& #39; t将其传递给removeEventListener以取消注册。相反,如上所述在类实例上定义回调。

相关问题