如何在React Native中检查互联网连接?

时间:2020-10-10 16:05:24

标签: react-native

我想在启动应用程序时检查互联网连接,然后要求用户连接互联网(如果没有)

2 个答案:

答案 0 :(得分:3)

您应该使用“ @ react-native-community / netinfo”库。 NetInfo曾经是react-native的一部分,但是后来它脱离了核心。如果要观察网络状态的变化,请使用提供的addEventListener方法。

import NetInfo from "@react-native-community/netinfo";

NetInfo.fetch().then(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
});

const unsubscribe = NetInfo.addEventListener(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
});

// Unsubscribe
unsubscribe();

答案 1 :(得分:0)

import NetInfo from "@react-native- 
community/netinfo";

NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});

const unsubscribe = NetInfo.addEventListener(state => 
{
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});