[英]I keep getting this TypeError: Cannot read property 'map' of undefined
I am trying to render this data from the API onto my page.我正在尝试将 API 中的这些数据呈现到我的页面上。 I am aware that what I am trying to render isn't in the typical array its a javascript object which is throwing me off.
我知道我要渲染的不是典型的数组,它的 javascript object 让我失望。 With my code, as is, the API data is there its just a matter of being able to access because.map isn't working because the data I have is not an array.
使用我的代码,API 数据只是能够访问的问题,因为。map 不起作用,因为我拥有的数据不是数组。 Do I need to create another function?
我需要创建另一个 function 吗?
I am not sure我不知道
import React from 'react';
import './App.css';
class App extends React.Component {
state = {
apiData: []
}
render() {
console.log('api datat is')
return (
<div>
<center>
<h1>hello something</h1></center>
{this.state.apiData.map(title => title.rendered)}
</div>
)
}
componentDidMount() {
fetch('http://www.mocky.io/v2/5dece3d333000052002b9037')
.then(response => response.json())
.then(data => {
this.setState({
apiData: data.data
})
})
console.log("component fetched data")
}
}
export default App
Any help would be great.任何帮助都会很棒。
I am still learning how to code so be nice我还在学习如何编码,所以要友善
Look at the API response:查看 API 响应:
{
"id": 233383,
"date": "2019-10-28T10:50:53",
"date_gmt": "2019-10-28T10:50:53",
"modified": "2019-10-28T10:55:14",
"modified_gmt": "2019-10-28T10:55:14",
"link": "https:\/\/www.stylist.co.uk\/long-reads\/friendship-friends-whatsapp-facebook-messenger-social-media-group-chat-best-friends-psychology-advice\/233383",
"title": {
"rendered": "Whatsapp and Facebook Messenger: how group chat is changing the dynamic of our friendships"
},
"slug": "whatsapp-and-facebook-messenger-how-group-chat-is-changing-the-dynamic-of-our-friendships",
etc.等等
It does not have a .data
property, so它没有
.data
属性,所以
.then(data => {
this.setState({
apiData: data.data
})
})
sets undefined
to this.state.apiData
.将
undefined
设置为this.state.apiData
。
The only rendered
exists in the one top-level object in the response, so you should remove the .map
entirely, something like:唯一
rendered
存在于响应中的一个顶级 object 中,因此您应该完全删除.map
,例如:
.then(data => {
this.setState({
apiData: data
})
})
<h1>hello something</h1></center>
{this.state.apiData.title.rendered}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.