React Native NetInfo判断网络状态

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
    Text,
    NetInfo,
    Toast
} from 'react-native';
// import NetWorkTool from './src/Net/NetWorkTool';
class Login extends Component {
    constructor(props){
        super(props);
        this.state={
            isConnected:null,
            connectionInfo:null
        }
    }

    componentDidMount() {
        //检测网络是否连接
        NetInfo.isConnected.fetch().done((isConnected)=>{
            this.setState({isConnected});
        });
    //    检测网络连接信息
        NetInfo.fetch().done((connectionInfo)=>{
            this.setState({connectionInfo});
        });
    //    检测网络变化事件
        NetInfo.addEventListener('change',(networkType)=>{
           this.setState({isConnected:networkType})
        })
    }
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>
                当前的网络状态:
                {this.state.isConnected?'网络在线':'离线'}
            </Text>
            <Text style={styles.welcome}>
                当前的网络连接类型:
                {this.state.connectionInfo}
            </Text>
            <Text style={styles.welcome}>
                当前连接的网络是否需要计费:
                {NetInfo.isConnectionExpensive===true?'需要':'不需要'}
            </Text>
            </View>
        );
    }

}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 30
    },
    welcome: {
        fontSize: 16,
        textAlign: 'left',
        margin: 10
    }
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容