[英]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.