首页 > 解决方案 > Net-info 发生错误在 React-Native 中不起作用

问题描述

我在我的代码中使用 Net-info 来检查互联网连接,但它对我不起作用。会报错。。

类型错误:未定义不是对象(正在评估'_reactNative.Netinfo.isConected')

我还在 AndroidManifest.xml 中设置了权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

但这对我不起作用

我的代码在这里..

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

export default class App extends Component{

  constructor(){

    super();

    this.state={

      connection_Status : ""

    }

  }

  componentDidMount() {

    NetInfo.isConnected.addEventListener(
        'connectionChange',
        this._handleConnectivityChange

    );

    NetInfo.isConnected.fetch().done((isConnected) => {

      if(isConnected == true)
      {
        this.setState({connection_Status : "Online"})
      }
      else
      {
        this.setState({connection_Status : "Offline"})
      }

    });
  }


  componentWillUnmount() {

    NetInfo.isConnected.removeEventListener(
        'connectionChange',
        this._handleConnectivityChange

    );

  }

  _handleConnectivityChange = (isConnected) => {

    if(isConnected == true)
      {
        this.setState({connection_Status : "Online"})
      }
      else
      {
        this.setState({connection_Status : "Offline"})
      }
  };

  render() {

    return (

      <View style={styles.MainContainer}>


        <Text style={{fontSize: 20, textAlign: 'center', marginBottom: 20}}> You are { this.state.connection_Status } </Text>


      </View>

    );

  }

}

const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    padding: 20
  },

  TextStyle: {
    fontSize:20,
    textAlign: 'center'
  }

});

如何解决这个问题请建议我任何解决方案。

标签: react-native

解决方案


我不知道你有什么版本的 React Native,但 netinfo 已被提取到不同的库中。

https://github.com/react-native-community/react-native-netinfo


推荐阅读