React Native App 因网络错误而崩溃 [英] React Native App crashes on Network error

查看:83
本文介绍了React Native App 因网络错误而崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React Native 开发一个文档上传应用程序.如果网络良好,文档会上传,但如果网络出现故障,应用程序会突然崩溃.例如 - 如果我在 4G 网络上上传文档,那么我会从 API 收到成功,但如果网络速度突然下降到 2G 网络,即 20KB/S,那么我会收到网络请求失败/网络错误"并且应用程序崩溃.

I am developing one document upload app, using react native. Documents get uploaded if the network is good, but suddenly the app crashes if the network goes down. For instance - If I am uploading the documents on 4G network then i receive success from API but if the network speed suddenly goes down to 2G network i.e. 20KB/S then I get "NETWORK REQUEST FAILED / NETWORK ERROR" and the app crashes.

我已经使用 catch 块处理了错误,但应用程序仍然崩溃,即使网络不可用或速度下降,我应该怎么做才能避免崩溃?

I have handled the error using catch block, but still the app crashes, what should I do to avoid this crashing even if the network is not available or if the speed goes down ?

下面是我的代码 -

try{
var form = FormData();
form.append("user_id",this.state.userId);
form.append('file', {
        uri: this.state.path,
        type: 'image/jpg',
        name: 'image.jpg',
});
axios({
method:"POST",
url:"http://xxxxx/xxxx",
timeout:50000,
data:form
})
.then(response => console.log(response))
.catch(error=>console.log(error));

}
catch(error){
console.log(error);
ToastAndroid.show("Internal error, please try again");
}

注意 - 我使用了 react-native-image-picker,因为文档可以使用相机拍摄,也可以从设备中的现有文件上传.

Note - I have used react-native-image-picker, as the document can be captured using camera OR it could be uploaded from the existing file present in the device.

还在清单文件中添加了所有访问互联网的权限.

Also have added all permissions in Manifest file for internet access.

请帮忙

推荐答案

那是一个例外.我想你需要捕捉异常BadNetwork 或 Timeout 你需要抓住它并且应用程序不应该崩溃只是确保在 Catch 您需要显示显示无法连接到服务器的对话框.或者您需要检查您是否有网络连接然后只让用户发送请求显示不可取消对话框希望有所帮助.

Thats an Exception. I guess you need to catch the Exception BadNetwork or Timeout You need to Catch it and App should not Crash just make sure In the Catch You need to Show the Dialog box which says Can't connect to server. OR You need to check if you have a Network connection then only Let the user send the Request show Non-cancelable Dialogbox Hope that helps .

这篇关于React Native App 因网络错误而崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆