【问题标题】:How to check internet connection in react native?如何在本机反应中检查互联网连接?
【发布时间】:2021-01-25 10:43:52
【问题描述】:

我想在启动应用程序时检查互联网连接,如果他没有连接到互联网,请让用户连接到互联网

【问题讨论】:

标签: react-native


【解决方案1】:

您应该使用“@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();

【讨论】:

  • 不错的答案 twboc
【解决方案2】:
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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    相关资源
    最近更新 更多