How to handle network failure in React-Native, when network is off

亡梦爱人 提交于 2019-12-08 15:20:58

问题


How to handle network failure in React-Native, when device not connected to network.

My scenario is am trying to connect some api, while fetching request if network is disconnected react-native throws network request failed error. how to handle this scenario to give the user best user experience.

How to handle Network request failed in a better way.


回答1:


Use NetInfo like this:

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



回答2:


Handle the exception using a catch block, from the catch block you can perform the action that handles the exception, may be a redirection or a state change to show the error

const url = `your url to be fetched`;
        fetch(url, {
          method: "GET",
          headers: header
        })
          .then(res => res.json())
          .then(json => {
            console.log(json);
             this.setState({
                data:json
              });  
    })
    .catch(error => {
      if (error) {
        //perform the redirection to the network request slow page or set state to show error
      }
    });



回答3:


You can try this to handle errors by fetch()

// 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) );


来源:https://stackoverflow.com/questions/36927007/how-to-handle-network-failure-in-react-native-when-network-is-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!