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)
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)
| 归档时间: |
|
| 查看次数: |
22555 次 |
| 最近记录: |