[英]React JSON API gives this.state.map not a function error
嘿,一段时间以来,我一直在努力寻找解决办法,我在这里和所有地方进行了搜索,但没有发现任何问题。
我有一个API,它包含嵌套数组,并通过JSON给出。
当我使用console.log时,我能够在JSON中显示内容,但是当我尝试映射数组时,我不断收到错误消息,指出.map函数存在问题。
从我所看到的情况来看,通常会发生这种情况,因为它不适用于字符串,但据我所知,它并未应用于字符串...
API中有很多数据,但是我敢肯定,一旦我知道如何只显示一个数据(例如日期),剩下的我就可以了。
这是代码
export default class App extends React.Component {
constructor() {
super();
this.state = {
myItem: []
};
}
componentDidMount() {
this.getItems();
}
getItems () {
fetch('MYAPIGOESHERE')
.then(results => results.json())
//THIS BELOW WORKS
.then(results => console.log(results.date, results.location));
//THIS BELOW AND THE RENDER DOES NOT
.then(myItem => this.setState({myItem}))
}
render() {
return (
<div>
{this.state.myItem.map (myItem =>
<div> {myItem.date} </div> )}
</div>
)
})
}
}
谢谢!
{"date":"2018-09-16T11:22:00.000Z","location":"Cardiff City Stadium","teams":[{"name":"Cardiff City","homeTeam":true,"formation":"4-4-2","players":[{"playerId":"5afc0b73b481e9b536c4727b","position":"GK"},{"playerId":"5afc1377b481e9b536c4727c","position":"RB"},{"playerId":"5afc188bb481e9b536c47299","position":"CB"},{"playerId":"5afc188ab481e9b536c47297","position":"CB"},{"playerId":"5afc1872b481e9b536c4727e","position":"LB"},{"playerId":"5afc1873b481e9b536c4727f","position":"RM"},{"playerId":"5afc1874b481e9b536c47280","position":"CM"},{"playerId":"5afc1876b481e9b536c47281","position":"CM"},{"playerId":"5afc1876b481e9b536c47282","position":"LM"},{"playerId":"5afc1876b481e9b536c47283","position":"FW"},{"playerId":"5afc1877b481e9b536c47284","position":"FW"}]},{"name":"Swansea City","homeTeam":false,"formation":"4-3-3","players":[{"playerId":"5afc187ab481e9b536c4728a","position":"GK"},{"playerId":"5afc1878b481e9b536c47286","position":"RB"},{"playerId":"5afc1879b481e9b536c47289","position":"CB"},{"playerId":"5afc187ab481e9b536c4728b","position":"CB"},{"playerId":"5afc187bb481e9b536c4728c","position":"LB"},{"playerId":"5afc1879b481e9b536c47288","position":"RM"},{"playerId":"5afc1878b481e9b536c47287","position":"CM"},{"playerId":"5afc187bb481e9b536c4728d","position":"LM"},{"playerId":"5afc187cb481e9b536c47290","position":"FW"},{"playerId":"5afc187db481e9b536c47291","position":"FW"},{"playerId":"5afc187db481e9b536c47292","position":"FW"}]}]}
尝试将setState放在大括号中:
.then(myItem => {
this.setState({myItem})
})
Map函数可用于数组,您似乎只有一个对象。 尝试这个:
return (
<div> {this.state.myItem.date} </div>
)
并删除地图和左括号之间的空间。
您无法在this.state.myItem
映射,因为它是一个对象。
您可以这样做:
<div>{this.state.myItem.date}</div>
如果有对象数组,则可以执行以下操作:
<div>{this.state.myItems.map(e => <div>{e.date}</div>)}</div>
例如。
如果您有一个带有数组的对象,则可以执行以下操作:
const { teams } = this.state.myItem;
<div>{teams.map(t => <div>{t}</div>)}</div>
您拥有的数据是这样的:Object-> Array-> Object,因此您可以结合以上内容来显示所需的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.