首页 > 解决方案 > React Native fetch API 不适用于 Android

问题描述

我是 React Native 开发的初学者。我开发了我的第一个 React Native 应用程序并在 Android 和 iOS 版本中启动。

在应用程序中,我使用 fetch API 与服务器通信。应用程序运行良好,并从 iOS 版本的 fetch API 获得响应。如果设备连接到高速网络连接(如 WiFi、4G ..),它在 Android 版本中也能正常工作。

但是,如果设备连接的网络连接不足,则 fetch API 不会在 Android 版本的应用程序中返回任何值(出现“网络连接失败”错误)。但在同一连接中,安装在同一设备中的其他应用程序运行良好。

我在用

react-native-cli: version 2.0.1
react-native: version 0.55.4
babel-preset-react-native: version 4.0.0,
Android compileSdkVersion 26
buildToolsVersion 23.0.1

这是我的获取 API 代码

getStudentList() {
var UrlDetails = URLDetails.getURLDetails();
return fetch(UrlDetails.SERVER_NAME + UrlDetails.GET_STUDENT_DETAILS_LIST_URL + 'student_id=1')
  .then((response) => response.json())
  .then((responseJson) => {
    let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    let isAllSet = responseJson.error;
    if (!isAllSet) {
      this.setState({
        isLoading: false,
        dataSource: ds.cloneWithRows(responseJson.student),
        isAllSetToShow: isAllSet,
      }, function () {
        activity_log = "received student details";
        this.updateDeviceLog();
      });
    } else {
      this.setState({
        isLoading: false,
        isAllSetToShow: isAllSet,
      }, function () {
        activity_log = "received response no student details";
        this.updateDeviceLog();
      });
    }
  })
  .catch((error) => {
    console.error(error);
    activity_log = JSON.stringify(error);
    Alert.alert('Alert',"Please check your internet connection!");
    this.updateDeviceLog();
  });

}

任何建议表示赞赏。

标签: androidreact-nativefetch-api

解决方案


推荐阅读