【发布时间】:2018-12-14 14:38:14
【问题描述】:
我正在调用 fetchData(url) 来检索 json 数据。我的 API 数据格式是这样的: 页号:1 页面大小:100 页数:5 总记录数:600 项目: 0:{ 编号:1, 主题:ACC } 1:{…}
我的反应 ItemList.js:
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;
它总是返回“加载项目时出错”。 Items 数组始终为空。但是,如果我将 api url 复制并粘贴到浏览器,它就可以正常工作。不确定我的代码有什么问题?谢谢。
【问题讨论】:
-
您的呼叫进入
catch块。从那里开始。在catch(()=>中添加错误参数,如catch((error)=>并检查。此外,您可以使用检查元素并在Network选项卡中查看您的请求。
标签: reactjs