【问题标题】:Losing connection during a fetch causes crash in React-Native app在获取期间丢失连接会导致 React-Native 应用程序崩溃
【发布时间】:2016-12-28 19:40:55
【问题描述】:

如果在我的 react-native 应用程序中获取期间互联网连接丢失,我会收到 Network request failed 并且应用程序崩溃。

  updateClientData() {

    var cachedData = null;

    AsyncStorage.getItem('cachedData').then((cachedDataString) => {  
       cachedData = JSON.parse(cachedDataString);     
    })

    .done(() => {

      if (cachedData) {
        const base64 = require('base-64');
        return fetch('https://...data.json', {
          method: 'get',
          headers: {
            'Authorization': 'Basic '+base64.encode("..."),
          }
        })

        .then( (response) => {
          // never called:
          return response.json();
        })

        .catch( (error) => {
          //Shouldn't this catch network errors? It never gets called.
          console.log('caught network error');
        })

        .then( (responseJSON) => {
            //do something with the JSON
        })

      } 

    });

  },

我希望能够优雅地处理这个问题,而不是让它崩溃。有什么想法吗?

【问题讨论】:

  • 如何将 catch 调用移到最底部而不是放在两个 then 调用之间?

标签: react-native fetch


【解决方案1】:

出于某种原因,将 AsyncStorage 调用移出此函数使其正常工作。无论如何,在我得到提取结果之前我实际上并不需要它,所以我移动了它。

现在可以了:

 updateClientData() {    

      const base64 = require('base-64');

      return fetch(clientListURL, {
        method: 'get',
        headers: {
          'Authorization': 'Basic '+base64.encode("..."),
        }
      })

      .then( (response) => {
        return response.json();
      })

      .catch( (error) => {
        console.log('error...')
      })

      .then( (responseJSON) => {
        // now do something with the JSON and the data from Async Storage
    }

  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多