首页 > 解决方案 > 应用程序关闭时是否删除了侦听器?

问题描述

假设我在以下位置注册了以下侦听器componentDidMount

    NetInfo.isConnected.addEventListener('connectionChange', this.props.connectionChange)

我需要该侦听器在应用程序运行时始终处于活动状态。

在这种情况下,是否需要调用removeEventListener或关闭应用程序后将其删除?

标签: javascriptreactjsreact-native

解决方案


您可以componentWillUnmount在状态为inactive

componentDidMount() {
  AppState.addEventListener('change', this.handleAppStateChange);
}

componentWillUnmount() {
   //remove listener here
  AppState.removeEventListener('change', this.handleAppStateChange);
}

handleAppStateChange = (nextAppState) => {
  if (nextAppState === 'inactive') {
     //remove listener here
  }    
}

希望这能解决您的问题


推荐阅读