如何在React Native iOS中查看网络信息? [英] How to check net Info in React Native iOS?

查看:100
本文介绍了如何在React Native iOS中查看网络信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查本机iOS中的互联网连接

我会尝试以下代码:

NetInfo.isConnected.fetch().then(isConnected => {
   console.log(isConnected);
});

可以在本机安卓应用程序中正常工作,
但它总是返回'false'在本机iOS中做出反应。

that can work fine in react native android application, But it always return 'false' in react native iOS .

推荐答案

目前在反应原生的github

你可以看到那里的讨论,但是简而言之 - fetch 总是返回 false ,但您可以通过侦听连接已更改事件来解决此问题。

You can see the discussion there, but in short - the fetch is always returning false, but you can work around it by listening to the connection changed event.

来自那里的代码示例:

componentDidMount() {
    NetInfo.isConnected.addEventListener('change', this.handleConnectionChange);

    NetInfo.isConnected.fetch().done(
      (isConnected) => { this.setState({ status: isConnected }); }
    );
}

componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('change', this.handleConnectionChange);
}

handleConnectionChange = (isConnected) => {
        this.setState({ status: isConnected });
        console.log(`is connected: ${this.state.status}`);
}

修改:

似乎这个问题已经工作
此外,更改事件已重命名为 connectionChange 。更新的解决方法代码:

Seems like this issue has been worked on. Also, change event was renamed to connectionChange. Updated workaround code:

componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange);

    NetInfo.isConnected.fetch().done(
      (isConnected) => { this.setState({ status: isConnected }); }
    );
}

componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectionChange);
}

handleConnectionChange = (isConnected) => {
        this.setState({ status: isConnected });
        console.log(`is connected: ${this.state.status}`);
}

已更新:

不推荐使用更改事件类型。考虑使用 connectionChange 事件类型。

The change event type is deprecated. Consider using the connectionChange event type.

这篇关于如何在React Native iOS中查看网络信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆