6

如何在設備未連接到網絡時處理React-Native中的網絡故障。如何在網絡關閉時處理React-Native中的網絡故障

我的場景是我試圖連接一些API,而如果網絡斷開連接提取請求反應原生拋出網絡請求失敗錯誤。如何處理這種情況以給用戶最好的用戶體驗。

如何處理網絡請求以更好的方式失敗。

enter image description here

回答

5

使用NetInfo這樣的:

// Check for network connectivity 
NetInfo.isConnected.fetch().done((isConnected) => { 
    if (isConnected) 
    { 
     // Run your API call 
    } 
    else 
    { 
     // Ideally load from local storage 
    } 
}); 
+0

總是顯示無法連接IOS。 –

0

你可以試試這個處理由抓取錯誤()

// Handling Internet Errors 


handleErrors(response) { 
    if (!response.ok) { 
     throw Error(response.statusText); 
    } 
    return response; 
    } 


fetch(/*"url"*/) 
    .then(this.handleErrors) 
    .then(response => console.log("ok")) 
    .catch(error => console.log(error));