问题
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