【发布时间】:2018-09-18 09:12:49
【问题描述】:
我刚开始学习 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>
)
}
}
有什么办法可以解决这个问题吗?
【问题讨论】:
-
你能看到实际的状态编号吗?不一定是每个错误都是 408
-
检查
response.ok可能会更可靠。 -
@CertainPerformance 如果没有连接或请求超时等其他响应呢?
-
@kurniawan26 那么响应就不行了
标签: javascript reactjs fetch-api