如何处理网络故障作出反应本地的,在未连接到网络的设备。
我的情况是我试图连接一些API,同时获取请求,如果网络中断反应本地抛出网络请求失败的错误。如何处理这种情况给用户最佳的用户体验。
如何处理以更好的方式失败的网络请求。
使用NetInfo是这样的:
// Check for network connectivity
NetInfo.isConnected.fetch().done((isConnected) => {
if ( isConnected )
{
// Run your API call
}
else
{
// Ideally load from local storage
}
});
使用catch块,从catch块可以执行处理异常的动作处理异常,可能是一个重定向或状态改变,显示错误
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
}
});
你可以试试这个处理由抓取错误()
// 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) );