【发布时间】:2018-03-06 20:18:48
【问题描述】:
我正在使用 fetch 方法使用下面编写的代码从我的 react 应用程序中的 API 检索数据。
componentDidMount(){
let auth_token = localStorage.getItem("token");
let header_obj = {"x-access-token": auth_token};
fetch('http://example.com/xyz', {headers: header_obj})
.then(response => response.json())
.then(response => {
this.setState({
postData:response.data //initially set to an empty array in constructor
})
})
.catch(err => {
console.log(err);
});
}
这很好用。它给了我确切的响应,即包含多个对象的数组
{
"data": [
{
"title": "John Doe",
"description": "Active User",
"dates": "4th Jan 2018"
},
{....} //multiple objects
]
}
现在,当我尝试从响应中访问任何对象时,例如
render() {
const {postData} = this.state;
return (
<div>
<h1>{postData[0].username}</h1>
</div>
)
}
这给了我一个错误“TypeError: Cannot read property 'username' of undefined "。我该如何解决这个问题?
【问题讨论】: