Pek*_*ica 7 reactjs react-native
我正在使用React Native 0.39构建一个原型应用程序,它从远程源请求一些数据.要发出请求,我使用Axios.
这个电话似乎很简单.在一个名为的组件中TownsList.js,我这样做
class TownsList extends Component {
constructor(props) {
super(props);
this.state = {towns: []};
}
componentDidMount() {
let url = "(SOME URL HERE)";
axios.get(url)
.then(function(response) {
// Do stuff witt the successful result
})
.catch(function (error) {
Alert.alert(
'Download failed',
'Unable to download data from '+url+"\nError:"+error,
[{text: 'OK'}])
});
...
Run Code Online (Sandbox Code Playgroud)
现在奇怪的是,每当我在// Do stuff witt the successful result块中的代码中遇到其他运行时错误时- 例如对某个常量或变量的错误引用 - 该错误也将由Axios的错误处理程序处理:
这感觉不对.我究竟做错了什么?我是否应该在我的应用程序中的其他位置设置"通用"错误处理以捕获这些内容?或者这是预期的行为?
Mal*_*lio 20
如果在您标记为的块中抛出错误,这是自然行为
// Do stuff witt the successful result
Run Code Online (Sandbox Code Playgroud)
如果您不想要这种行为,请考虑以这种方式编写它:
axios.get(url)
.then(function(response) {
// Do stuff with the successful result
},
function (error) {
// any error from the get() will show up here
Alert.alert(
'Download failed',
'Unable to download data from '+url+"\nError:"+error,
[{text: 'OK'}])
});)
})
.catch(function(error) {
// any error from "doing stuff" will show up here
console.error(error);
})
Run Code Online (Sandbox Code Playgroud)
该.then()方法允许两个函数,一个用于成功,另一个用于失败 - 原始承诺的失败,而不是成功函数.
由于您自己的代码本身由于某种原因而失败,您当然不希望沉默.
| 归档时间: |
|
| 查看次数: |
3032 次 |
| 最近记录: |