react原生网络丢失检查



如何检查反应式本机网络失去连接?我尝试了下面的代码,它抛出了一个错误。我想显示和警报时,应用程序失去了它的网络连接?

CheckConnectivity = () => {
// For Android devices
if (Platform.OS === "android") {
NetInfo.isConnected.fetch().then(isConnected => {
console.log(isConnected,">>>")
if (isConnected) {
Alert.alert("You are online!");
} else {
Alert.alert("You are offline!");
}
});
} else {
// For iOS devices
NetInfo.isConnected.addEventListener(
"connectionChange",
this.handleFirstConnectivityChange
);
}
};
handleFirstConnectivityChange = isConnected => {
NetInfo.isConnected.removeEventListener(
"connectionChange",
this.handleFirstConnectivityChange
);
if (isConnected === false) {
Alert.alert("You are offline!");
} else {
Alert.alert("You are online!");
}
};
<代码>

看起来您使用了错误的API。例如,这是WEB

PP_3如果你在这里检查:https://github.com/react-native-netinfo/react-native-netinfo/blob/ba5c22cf2045b690243984a548ee25f4f6371e4a/src/internal/nativeModule.web.ts#L59

你需要遵循这个例子:

https://github.com/react-native-netinfo/react-native-netinfo/blob/master/example/IsConnected.tsx

https://github.com/react-native-netinfo/react-native-netinfo/blob/master/example/ConnectionInfoSubscription.tsx

最新更新