React Native中的NetInfo问题-Android

时间:2018-08-21 10:44:58

标签: react-native

netInfo在我的android设备中无法正常运行。有时它仍然有效。我已将isConnected状态初始化为false,即使存在网络连接,它也始终保持false状态。为什么netInfo无法正常工作?我正在android设备中对其进行测试。下面是我的代码。预先感谢。

function MiniOfflineSign() {
  return (
    <View>
      <Text>No Internet Connection</Text>
    </View>
  );
}

export default class App extends Component<Props> {
  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      isConnected: false,
    };
  }

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
    console.log('netInfo', this.state.isConnected);
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
    console.log('netInfo1', this.state.isConnected);
  }


  handleConnectivityChange = isConnected => {
    if (isConnected) {
      this.setState({ isConnected });
      fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource: responseJson.movies,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
    } else {
      this.setState({ isConnected });
    }
  };

  render() {
    if (!this.state.isConnected) {
      return <MiniOfflineSign />;
    }else{
        if (this.state.isLoading) {
          return (
            <View style={{ flex: 1, padding: 10 }}>
              <ActivityIndicator size="large" color="#ff0000" />
            </View>
          );
        }
    }
    return (
      <View style={{flex: 1, paddingTop:20}}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>}
          keyExtractor={(item, index) => index}
        />
      </View>
    );

  }
}

0 个答案:

没有答案