React-native 中的应用程序状态不会删除侦听器

gbh*_*ati 18 react-native react-native-ios

我通过以下方式添加了侦听器(尝试同时放入构造函数和 componentDidMount): AppState.addEventListener('change', this._handleAppStateChange);

并在 componentWillUnmount 方法中通过以下方式删除了侦听器:

AppState.removeEventListener('change', this._handleAppStateChange);

并且在回调函数中:

  _handleAppStateChange = (nextAppState) => {
    setTimeout(() => {
      alert('App state: ' + this.state.appState);
      alert('Next App state: ' + nextAppState);
    }, 0);
  }
Run Code Online (Sandbox Code Playgroud)

它会提醒几次。它不会删除一次配置的侦听器。如果有人知道的话请告诉我?

Joh*_*rer 35

根据最新文档(2021 年 9 月 v0.65+)removeEventListener已弃用

文档现在建议在从 . 返回的remove订阅对象 ( ) 上使用该函数。EmitterSubscriptionAppState.addEventListener

用法示例:

const subscription = AppState.addEventListener('change', (appState) => {
  if (appState !== 'active') {
    return;
  }

  // Run custom logic

  subscription.remove();
});
Run Code Online (Sandbox Code Playgroud)

  • 然而,似乎 `AppState.addEventListener` 实际上并没有返回 `remove` 方法。文档中给出的示例也不起作用。 (3认同)
  • 我正在使用 Expo,所以我猜他们还没有添加对最新版本的 React Native 的支持。然而,使用“.removeEventListener”的旧方法仍然有效。不管怎么说,还是要谢谢你! (2认同)

Yad*_*GİN 18

你应该像现在一样使用 API

useEffect(() => {
 const myListener = AppState.addEventListener('change', this.someHandler)
 return () => {
   myListener.remove()
 }
}, [])
Run Code Online (Sandbox Code Playgroud)


小智 0

您必须从ComponentWillUnmount函数中删除侦听器

componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }
Run Code Online (Sandbox Code Playgroud)