繁体   English   中英

没有网络连接时,React Native IOS App崩溃

[英]React Native IOS App crashes when no network conection

在模拟器上,它不会崩溃并发出错误警报,但在生产环境中,只要提出提取请求,它就会崩溃,并且在网络连接恢复之前,无法重新打开应用程序(我为飞机打开/关闭飞行模式测试)

这是我的代码片段

  componentWillMount: function(){
    NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange)
    NetInfo.isConnected.fetch().done((data) => {

    this.setState({
      isConnected: data
    })
    console.log('this.state.isConnected: ', this.state.isConnected);
  })
 },

handleConnectivityChange: function(){
  var connected = this.state.isConnected ? false : true
  this.setState({isConnected: connected})
  console.log('this.state.isConnected11: ', this.state.isConnected);
},

....

goToList: function(replace, listview){
  console.log('this.state.isConnected: ', this.props.isConnected);
  if (!this.props.isConnected){
    AlertIOS.alert('Error', 'Please check your network connectivity')
    this.props.removeFetching()
    return
  }
 ....
 fetch(url)
  .then((response) => response.json())
  .then((responseData) => {
 ....
  .catch((error) => {
  StatusBarIOS.setNetworkActivityIndicatorVisible(false)
  AlertIOS.alert('Error', 'Please check your network connectivity')
  this.props.removeFetching()
 })
.done()

我花了很多时间试图找到一种使用fetch()时捕获异常的方法,但是我无法使其正常工作(例如,使用.catch()或try / catch博客不起作用)。 起作用的是将XMLHttpRequest与try / catch博客一起使用,而不是fetch()。 这是我基于的示例: https : //facebook.github.io/react-native/docs/network.html#using-other-networking-libraries

var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
  if (request.readyState !== 4) {
    return;
  }

  if (request.status === 200) {
    console.log('success', request.responseText);
    var responseJson = JSON.parse(request.responseText);
    // *use responseJson here*
  } else {
    console.warn('error');
  }
};
try {
  request.open('GET', 'https://www.example.org/api/something');
  request.send();
} catch (error) {
  console.error(error);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM