我刚刚开始学习ReactJS。现在,我想知道在使用fetch发出API请求时如何处理响应状态。这是我的代码:
componentDidMount(){
this.setState({ isLoading: true })
var id = this.props.match.params.id
const api = `bla/bla/${id}`;
console.log("start call api")
fetch(api)
.then((response) => {
if(response.status === 200){
console.log("SUCCESSS")
return response.json();
}else if(response.status === 408){
console.log("SOMETHING WENT WRONG")
this.setState({ requestFailed: true })
}
})
.then((data) => {
this.setState({ isLoading: false, downlines: data.response })
console.log("DATA STORED")
})
.catch((error) => {
this.setState({ requestFailed: true })
})
console.log("end call api")
}
我关闭了连接以进行的测试408
,但仍然显示我的负载。
render(){
const { isLoading, requestFailed } = this.state;
if(requestFailed){
return(
<div className="errorContainer">
<a className="errorMessage">Opss.. Something went wrong :(</a>
</div>
)
}
}
有解决这个问题的想法吗?
根据MDN文档:
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
当遇到网络错误或在服务器端未正确配置CORS时,fetch()承诺将以TypeError拒绝,尽管这通常意味着权限问题或类似问题,例如404并不构成网络错误。准确检查成功的fetch()包括检查已解决的诺言,然后检查Response.ok属性的值为true。代码看起来像这样:
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ',
error.message);
});
查看您的代码,我认为您的408错误检查永远不会运行。我认为事实并非如此。基本上,上面的代码正在执行的操作是,如果请求为200ish正常,则返回json响应,否则将引发错误。如果发生错误,那么您的第二个错误将永远不会运行,并且会被扔到catch块中。也许您可以在其中设置isLoading:false?
另外,您在api的结尾的日志语句不正确。这是在您的诺言完成之前被调用的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句