ReactNative: 使用NetInfo獲取網絡狀態


一、簡介

網絡監聽,這是App開發中必不可少的功能。開發者會根據網絡狀態的不同,對App采取不同的應對措施來應對網絡問題。例如,在WIFI狀態下,用戶可以瀏覽大圖或者自動播放視頻,在離線狀態下,要關閉正在加載的Loading,通過提示用戶網絡狀態不好,以避免長時間等待,提高用戶體驗。在iOS移動端開發中,我們一般會使用AFN第三方框架中的AFNetWorkingReachability這個類來監聽網絡。同樣地,ReactNative中也提供了一個監聽網絡的API,就是NetInfo。

 

二、API

屬性:

NetInfo提供了屬性isConnected來獲取網絡連接對象

//獲取設備是否具備網絡連接對象: 包含三個函數:添加監聽、移除監聽、獲取網絡狀態的函數
console.log('NetInfo.isConnected:',NetInfo.isConnected);

iOS平台中提供的網絡枚舉類型

//離線狀態
none

//在線狀態,並通過WIFI或者iOS模擬器連接
wifi

//網路連接,通過3/4G、WiMax或者LTE進行連接
cell

//錯誤情況,網絡狀態未知
unknown

函數:

1、fetch():  獲取網絡狀態,可以是網絡枚舉類型,也可以是網絡連接情況。

//獲取網絡枚舉類型
NetInfo.fetch().then(function (reachability) {
     console.log('network type:'+reachability);
});

//獲取網絡連接情況
NetInfo.isConnected.fetch().then(function (isConnected) {
     console.log('current network status:' + (isConnected ? 'online' : 'offline'));
});

2、addEventListener(eventName: ChangeEventName, handler: Function):添加網絡監聽事件

//添加網絡類型監聽
NetInfo.addEventListener('change', function (reachability) {
    console.log('network type change hanpend, network type:'+reachability);
});

//添加網絡連接監聽
NetInfo.isConnected.addEventListener('change',function (isConnected) {
     console.log('network status change happened, isConnected = '+ isConnected);
});

3、removeEventListener(eventName: ChangeEventName, handlerFunction):移除網絡監聽事件

//移除網絡類型監聽
NetInfo.removeEventListener('change', function (reachability) {
     console.log('after remove, network type:'+reachability);
});

//移除網絡連接監聽
NetInfo.isConnected.removeEventListener('change', function (isConnected) {
     console.log('after remove, network status:'+isConnected);
});

 

三、使用

現在來測試一下API的使用,示例如下:

index.ios.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';

import {
    AppRegistry,
    StyleSheet,
    View,
    Text,
    NetInfo
} from 'react-native';


export default class ReactNativeDemo extends Component {

    constructor(){
        super();

        //獲取設備是否具備網絡連接對象: 包含三個函數:添加監聽、移除監聽、獲取網絡狀態
        console.log('NetInfo.isConnected:',NetInfo.isConnected);

        //添加網絡類型監聽,變化過程中,返回枚舉類型
        NetInfo.addEventListener('change', function (reachability) {
            console.log('network type change happened, network type:'+reachability);
        });

        //添加網絡連接監聽,變化過程中,返回布爾值
        NetInfo.isConnected.addEventListener('change',function (isConnected) {
            console.log('network status change happened, isConnected = '+ isConnected);
        });
    }

    componentDidMount() {

        //獲取網絡類型,返回枚舉值
        NetInfo.fetch().then(function (reachability) {
            console.log('current network type:'+reachability);
        });

        //獲取網絡連接,返回布爾值
        NetInfo.isConnected.fetch().then(function (isConnected) {
            console.log('current network status:' + (isConnected ? 'online' : 'offline'));
        });
    }

    componentWillUnmount() {

        //移除網絡類型監聽
        NetInfo.removeEventListener('change', function (reachability) {
            console.log('after remove, network type:'+reachability);
        });

        //移除網絡連接監聽
        NetInfo.isConnected.removeEventListener('change', function (isConnected) {
            console.log('after remove, network status:'+isConnected);
        });
    };


    render() {
        return (
            <View style={[styles.flex,styles.bgColor,styles.center]}>
                <Text/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    flex: {
        flex: 1
    },
    bgColor: {
      backgroundColor: '#1FB9FF'
    },
    center: {
        alignItems: 'center',
        justifyContent: 'center'
    }
});

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);

xcode日志如下:

2019-12-31 14:25:06.664 [info][tid:com.facebook.react.JavaScript] 'NetInfo.isConnected:', { addEventListener: [Function: addEventListener],
  removeEventListener: [Function: removeEventListener],
  fetch: [Function: fetch] }
2019-12-31 14:25:06.694 [info][tid:com.facebook.react.JavaScript] network type change happened, network type:wifi
2019-12-31 14:25:06.694 [info][tid:com.facebook.react.JavaScript] network status change happened, isConnected = true
2019-12-31 14:25:06.704 [info][tid:com.facebook.react.JavaScript] current network type:wifi
2019-12-31 14:25:06.705 [info][tid:com.facebook.react.JavaScript] current network status:online

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM