简体   繁体   English

在我的 React Native 项目中没有显示互联网连接

[英]show no internet conection in my react native project

I'm new in react native, I made simple project that gives data from API now, I want to show notice if I'm offline then show message or alert我是 React Native 的新手,我做了一个简单的项目,现在提供来自 API 的数据,如果我离线,我想显示通知然后显示消息或警报

no internet connection没有网络连接

is there a helpful library?有没有有用的图书馆? and how can I use it?我该如何使用它?

thanks谢谢

Don't use Library React Native has API called NetInfo to check the network不要使用Library React Native有名为NetInfo API来检查网络

From my experience Android and IOS needs separate codes .根据我的经验, AndroidIOS需要单独的codes

I will give you my approach.我会给你我的方法。

First create a utils file NetworkUtils.js首先创建一个utils file NetworkUtils.js

Code below :下面的代码:

import { NetInfo } from 'react-native';

export function addNetworkCheckListener(callback) {
    NetInfo.isConnected.addEventListener('connectionChange', callback);
}

export function removeNetworkCheckListener() {
    NetInfo.isConnected.removeEventListener('connectionChange');
}

export function isNetworkAvailable(callback) {
    NetInfo.isConnected.fetch().then(isConnected => {
        callback(isConnected);
    });
}

In my case i checked it in Login.js就我而言,我在Login.js检查了它

Import the functions from util file to your needed file.将 util 文件中的函数导入到您需要的文件中。

code below :下面的代码:

import {
    isNetworkAvailable as isNetAvail,
    addNetworkCheckListener,
    removeNetworkCheckListener
} from '../../Utils/NetworkUtils';

   constructor(props) {
        super(props);
         this.isNetworkAvailableBinder = this.isNetworkAvailableBinder.bind(this);
    }

componentDidMount() {
    addNetworkCheckListener(this.isNetworkAvailableBinder);
    if (isAndroid()) {
            this.checkAndroidNetworkAvailable();
        }
}

componentWillUnmount() {
    removeNetworkCheckListener(this.isNetworkAvailableBinder);
}

checkAndroidNetworkAvailable() {
    isNetAvail((isConnected) => {
        // Check isConnected for ANDROID
       if(isConnected){
          alert("Connected to internet");
         }
      else {
          alert(" Not connected to internet");
       }
    });
}

isNetworkAvailableBinder(isConnected) {
        // Check isConnected for IOS
     if(isConnected){
          alert("Connected to internet");
         }
      else {
          alert(" Not connected to internet");
       }
 }

You can use below code to solve your issue您可以使用以下代码来解决您的问题

import {NetInfo} from "react-native";
componentDidMount() {

    NetInfo.isConnected.addEventListener(
      "connectionChange",
      this.handleConnectivityChange
    );
  }
  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener(
      "connectionChange",
      this.handleConnectivityChange
    );
  }
 handleConnectivityChange = isConnected => {
    if (isConnected) {
      this.setState({ isConnected });
    } else {
      alert("Oops!! No Internet Connection Available");
      this.setState({ isConnected });
    }
  };

Simply call a alert function if there is no response from an api, like below UserLogin = async () =>如果 api 没有响应,只需调用警报函数,如下所示 UserLogin = async () =>

{
        fetch('http://your api', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                phone: this.state.Phonenumber,
                password: this.state.Password,
            })
        })
            .then((response) => response.json())
            .then((responseData) => {
                if (responseData) {
                  Alert.alert(responseData.message);

                } else {
                    Alert.alert(responseData.message);
                }
            })
            .catch((error) => {
                Alert.alert('No Internet Connection');
            })
    }

Following the material desgin, you should use the react-native-sackbar按照材料设计,您应该使用react-native-sackbar

And Use the React Native's API NetInfo to check the network.并使用 React Native 的 API NetInfo检查网络。

Cheer!欢呼!

React native has a native library named Netinfo that permits you to get that information. React Native 有一个名为Netinfo的本机库,它允许您获取该信息。 Example :例子 :

import {NetInfo} from 'react-native';

NetInfo.isConnected.addEventListener('connectionChange', (hasInternetConnection) = console.debug(`hasInternetConnection:`, hasInternetConnection));
export default class InternetConnectionPopUp extends Component {
    constructor(props) {
        super(props);
        this.state = {connectionInfo: ''}
        this.handleFirstConnectivityChange = this.handleFirstConnectivityChange.bind(this);
    }
    handleFirstConnectivityChange(connectionInfo) {
        this.setState({connectionInfo: connectionInfo.type})
    }

    componentDidMount() {
        NetInfo.getConnectionInfo().then((connectionInfo) => {
            this.setState({connectionInfo: connectionInfo.type})
        });
        NetInfo.addEventListener('connectionChange',this.handleFirstConnectivityChange);
    }

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

    render() {
        const { connectionInfo } = this.state
        connectionInfo == 'none' ?
                <Modal
                visible={true}
                animationType={'slide'}
                transparent
                onRequestClose={() => {}}
                >
                    <Text>No Internet Connection</Text>
                </Modal>
            :
            null
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM