编程语言
首页 > 编程语言> > javascript – 使用反馈JS中的fetch处理响应状态

javascript – 使用反馈JS中的fetch处理响应状态

作者:互联网

我刚开始学习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>
        )
    }
}

这是我浏览器中的日志:
enter image description here

有什么想法解决这个问题?

解决方法:

根据MDN文档:

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:

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错误检查不会运行.我认为事实并非如此.基本上上面的代码正在做的是如果请求是200的确定则返回json响应,否则它会抛出错误.如果发生错误,那么你的第二个错误就永远不会运行,它会被抛到catch块.也许你可以设置isLoading:false吗?

你也是api结束的日志声明不正确.这是在你的承诺完成之前被调用的.

标签:fetch-api,javascript,reactjs
来源: https://codeday.me/bug/20190823/1697551.html