最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detect if the user is connected to the internet? - Stack Overflow

programmeradmin2浏览0评论

I'd like to route the user to a certain screen, in case he is not connected to the internet.

I just can't detect if he is connected or not.

I tried this code, but did not work:

async componentWillMount()
{
   if (!await NetInfo.isConnected)
   {
      this.props.navigation.navigate('Saved');
   }
}

Any tested solution to suggest?

I'd like to route the user to a certain screen, in case he is not connected to the internet.

I just can't detect if he is connected or not.

I tried this code, but did not work:

async componentWillMount()
{
   if (!await NetInfo.isConnected)
   {
      this.props.navigation.navigate('Saved');
   }
}

Any tested solution to suggest?

Share Improve this question edited Jul 19, 2018 at 9:15 Hardik Shah 4,2002 gold badges21 silver badges44 bronze badges asked Jul 19, 2018 at 8:24 27mdmo7sn27mdmo7sn 5092 gold badges6 silver badges15 bronze badges 4
  • Possible duplicate of Detect network connection in React Redux app - if offline, hide component from user – vahdet Commented Jul 19, 2018 at 8:28
  • 1 @vahdet are you sure that the same browser APIs that the linked question uses are available in react-native? – Al.G. Commented Jul 19, 2018 at 8:38
  • 1 At the time of the comment, react was among the tags. Not deleteing in case of it could be a helpful link to anyone some time though. Thanks! – vahdet Commented Jul 19, 2018 at 8:58
  • 1 Here's an interesting article medium.com/@kulor/… about why NetInfo isn't necessary the best approach. It explains that NetInfo reports a User as connected when they're connected to a WiFi behind a paywall. The article poses a solution. – Dan Commented Jul 19, 2018 at 17:22
Add a comment  | 

5 Answers 5

Reset to default 8

Try await NetInfo.isConnected.fetch()

ref : https://facebook.github.io/react-native/docs/netinfo.html#isconnected

You can check using NetInfo . for that you have to add connectionChange event listener like this

componentDidMount() {
        NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange.bind(this));
        NetInfo.isConnected.fetch().done(
            (isConnected) => { this.setState({ isConnected: isConnected }); }
        );

and then remove the event listener in componentWillUnmount

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

And finally the handler method for connection change. I am storing the status in device local storage you can do whatever you want.

handleConnectionChange = (isConnected) => {
        if (isConnected) {
            //ToastAndroid.show('Data sync in process...', ToastAndroid.SHORT);
            AsyncStorage.getItem('offlineData')
                .then((json) => JSON.parse(json))
                .then((data) => {
                    console.log(JSON.stringify(data));
                });
        }
        else { ToastAndroid.show('You are offline.', ToastAndroid.SHORT); }

        this.setState({ isConnected: isConnected });
    }

Don't forget to add NetInfo from react-native :)

Another solution to your case (one without using isConnected property) is to use the object returned from the event handler directly like that:

componentDidMount() {
  NetInfo.addEventListener('connectionChange', this.handleNetworkChange);
}

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

handleNetworkChange = (info) => {
    if (info.type === 'none') {
      this.props.navigation.navigate('Saved');
    }
};

According to NetInfo documentation:

connectionChange event fires when the network status changes. The argument to the event handler is an object with keys:

type: A ConnectionType (listed above)

effectiveType: An EffectiveConnectionType (listed above)

The connection type can be one of the following : none, wifi, cellular, unknown.

Ideally you can store this information to your redux store and the listener to a root component.

We had a weird bug when using isConnected similar to the one you mentioned @Gabriel Bleu but for us, the NetInfo.isConnected.fetch() returned false only when the Android device was awake after some period of inactivity.We used it to display offline warning for users, so the warning never left. I found this solution on a Spencer Carli's course and it seems to work better but depending on your needs, you might want to use isConnected combined with the above code.

This is a great example to check online or offline and even you can have connection change information too. Source

NetInfo.isConnected.fetch().then(isConnected => {
  console.log('First, is ' + (isConnected ? 'online' : 'offline'));
});
function handleFirstConnectivityChange(isConnected) {
  console.log('Then, is ' + (isConnected ? 'online' : 'offline'));
  NetInfo.isConnected.removeEventListener(
     'connectionChange',
     handleFirstConnectivityChange
  );
}
NetInfo.isConnected.addEventListener(
  'connectionChange',
  handleFirstConnectivityChange
);

There are two issues with your code currently.

  1. In newer versions of react life-cycle method componentWillMount is deprecated.
  2. Newer versions of react-native have extracted the NetInfo Module out of the core. Use @react-native-community/netinfo instead.

In order to achieve the desired behavior you should do something like this.

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

class CheckConnection extends Component {

    componentDidMount() {
        
        NetInfo.fetch().then(state => {
            handleConnectionState(state)
        }); 
        
    }
        
    handleConnectionState(state) {
        console.log("Connection type", state.type);
        console.log("Is connected?", state.isConnected);
        ... your code to handle the lack of connection
        
    }

}
发布评论

评论列表(0)

  1. 暂无评论