Reactjs 在React中获取API数据
我正在调用fetchDataurl来检索json数据。我的API数据格式如下: 页码:1 页面大小:100 页数:5 TotalRecordCount:600 项目: 0: { ID:1, 主题:行政协调会 } 1:{…} My react ItemList.js:Reactjs 在React中获取API数据,reactjs,Reactjs,我正在调用fetchDataurl来检索json数据。我的API数据格式如下: 页码:1 页面大小:100 页数:5 TotalRecordCount:600 项目: 0: { ID:1, 主题:行政协调会 } 1:{…} My react ItemList.js: import React, {Component} from 'react'; class ItemList extends Component{ constructor(){ super(); this.state
import React, {Component} from 'react';
class ItemList extends Component{
constructor(){
super();
this.state={
Items:[],
hasErrored: false,
isLoading: false
};
}
//retrieve data using fetch
fetchData(url){
this.setState({isLoading: true});
fetch(url)
.then((response)=>{
if (!response.ok){
throw Error(response.statusText);
}
this.setState({isLoading:false});
return response;
})
.then((response)=>{response.Items.json()})
.then((Items)=>{
this.setState({Items});
})
.catch(()=>this.setState({hasErrored:true}));
}
componentDidMount(){
this.fetchData(myURL)
}
render(){
if (this.state.hasErrored){
return <p>There was an error loading the items</p>;
}
if (this.state.isLoading){
return <p>Loading...</p>;
}
return(
<div>
<ul>
{this.state.Items.map((item)=>(
<li key={item.ID}>{item.SUBJECT}</li>
))}
</ul>
</div>
);
}
}
export default ItemList;
它总是返回加载项目时出错的消息。项目数组始终为空。但如果我将api url复制并粘贴到浏览器上,它就可以正常工作。不确定我的代码出了什么问题?谢谢。我想应该是这样的:
fetch(url)
.then((response)=>{
if (!response.ok){
throw Error(response.statusText);
}
this.setState({isLoading:false});
return response.json();
})
.then((resp)=>{
this.setState({Items: resp.Items});
})
.catch(()=>this.setState({hasErrored:true}));
response.Items.json
这一行将抛出一个错误,因为在将响应转换为JSON格式之前,它还只是一个字符串
使用
response.json
然后,我将@Kabbany answer更改为response.statusText始终返回与错误代码关联的一般错误消息。然而,大多数API通常会在体内返回某种有用的、更人性化的消息
关键是不要抛出错误,只需抛出响应,然后在catch块中对其进行处理,以提取正文中的消息:
fetch(url)
.then( response => {
if (!response.ok) { throw response } // Return the complete error response for debugging purposes
return response.json() //we only get here if there is no error
})
.then( json => {
this.setState({Items: json.Items });
})
.catch( error => {
() => this.setState({ hasErrored: true, error }) // Save both error flag and error detail so you can send it to tools like bugsnag
})
您的呼叫进入了catch块。从那里开始。在catch=>中添加error参数,如catcherror=>并进行检查。此外,您还可以使用inspect元素并在网络选项卡中查看您的请求。谢谢,但我尝试了Items:resp.Items,但它不起作用。无论如何,您缺少了一个很大的部分,即response.json,如果没有它,响应将无法以json格式提供