React native Netinfo连接更改事件侦听器未分离
我在启动屏幕组件DidMount上添加了connectionChange事件侦听器,但在组件WillUnmount上没有删除它。它在应用程序的每个页面上都处于活动状态。如何在componentWillUnmount上分离它React native Netinfo连接更改事件侦听器未分离,react-native,React Native,我在启动屏幕组件DidMount上添加了connectionChange事件侦听器,但在组件WillUnmount上没有删除它。它在应用程序的每个页面上都处于活动状态。如何在componentWillUnmount上分离它 componentDidMount() { NetInfo.addEventListener('connectionChange', (networkType)=> { this.handleFirstConnectivityC
componentDidMount() {
NetInfo.addEventListener('connectionChange',
(networkType)=> {
this.handleFirstConnectivityChange({networkType})
}
}
componentWillUnmount() {
this.notificationListener.remove();
NetInfo.removeEventListener(
'connectionChange'
);
}
您需要将在
addEventListener
中使用的相同回调传递到removeEventListener
:
class SomeClass extends Component {
handleConnectivityChange = networkType => {
//...
};
componentDidMount() {
NetInfo.addEventListener(
"connectionChange",
this.handleConnectivityChange
);
}
componentWillUnmount() {
NetInfo.removeEventListener(
"connectionChange",
this.handleConnectivityChange
);
}
}
请注意,在调用
addEventListener
时,不应创建新的arrow函数包装器,因为您没有对该函数实例的引用,并且无法将其传递给removeEventListener
以取消注册。相反,在类实例上定义回调,如上所述。您确定调用了componentWillUnmount
吗?是的,我对其发出了消息警报。有人叫它。