Javascript 在 React JS 中使用 fetch 处理响应状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49725012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling response status using fetch in react JS
提问by kurniawan26
I just started learning ReactJS. Now I want to know how to handle response status when I make an API request using fetch. Here's my code :
我刚开始学习 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")
}
I turned off my connection to make a test for 408, but my loading is still appears.
我关闭了我的连接以进行测试408,但我的加载仍然出现。
render(){
const { isLoading, requestFailed } = this.state;
if(requestFailed){
return(
<div className="errorContainer">
<a className="errorMessage">Opss.. Something went wrong :(</a>
</div>
)
}
}
Any ideas to fix this ?
任何想法来解决这个问题?
回答by Charles Owen
According to MDN documentation:
根据 MDN 文档:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. The code would look something like this:
当遇到网络错误或 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);
});
Looking at your code, I don't think your 408 error check will ever run. I don't think it did in fact. Basically what the code above is doing is returning the json response if the request is 200ish ok, otherwise it's throwing an error. If an error occurs, your second then never runs and it gets thrown to your catch block. Perhaps you can set the isLoading: false there?
查看您的代码,我认为您的 408 错误检查永远不会运行。我认为事实上并没有。基本上上面的代码所做的是如果请求是 200ish 就返回 json 响应,否则它会抛出错误。如果发生错误,则您的第二个将永远不会运行并被抛出到您的 catch 块。也许您可以在那里设置 isLoading: false ?
Also you're log statement for end of api isn't correct. That's being called before your promise completes.
此外,您对 api 结束的日志语句不正确。这是在你的承诺完成之前被调用的。
回答by CertainPerformance
Throw an error when the response is not OK so that it proceeds directly to the catch:
当响应不正常时抛出一个错误,以便它直接进入catch:
fetch(api)
.then((response) => {
if(!response.ok) throw new Error(response.status);
else return response.json();
})
.then((data) => {
this.setState({ isLoading: false, downlines: data.response });
console.log("DATA STORED");
})
.catch((error) => {
console.log('error: ' + error);
this.setState({ requestFailed: true });
});


