React Native + Expo:ネットワークへの接続・切断を検出する

検出にはNetinfoを用います。まず、

expo install @react-native-community/netinfo

でインストールしてください。

import * as React from 'react';
import NetInfo from '@react-native-community/netinfo';
import { StyleSheet, Text, View, Alert } from 'react-native';
import { withNavigationFocus } from 'react-navigation';
import { Button } from 'react-native-elements';

class screenA extends React.Component {

  state = {
    isConnected: false,
  }

  async componentDidMount() {
    const unsubscribe = NetInfo.addEventListener( state => {
      if (this.state.isConnected && ! state.isConnected) {
        this.setState({
          isConnected: false
        });
      }
      if (!this.state.isConnected && state.isConnected) {
        this.setState({
          isConnected: true
        });
      }
    });
  }

  render () {
    if (this.state.isConnected) {
      return (
        <View>
          <Text>{'\n'}This is screen A, connected</Text>
        </View>
      );
    } else {
      return (
        <View>
          <Text>{'\n'}This is screen A, NOT connected</Text>
        </View>
      );
    }
  }
}

export default withNavigationFocus(screenA);