App.js 我面臨這個問題檔案錯誤 - Uncaught TypeError: items.data.map is not a function。我嘗試了其他一些選擇,但沒有奏效。我似乎無法找到我做錯了什么。
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,
DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Loading data ... </h1> </div> ;
return (
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.data.map((item) => (
<ol key = { item.data} >
Continents: {item.data[0]}
</ol>
))
}
</div>
);
}
}
export default App;
JSON資料
來自 json 資料型別的嵌套 API 資料。
{
"data": {
"data": [
{
"project_id": "xxxx",
"title": "xxx34",
"description": "xxx23",
"expense": 1699126,
"budget": 6418516,
"country": "xxx",
"sector": [
{
"name": "Accelerate structural transformations",
"code": "18"
}
],
"sdg": [
{
"name": "Peace, justice, and strong institutions",
"id": "16"
}
],
"signature_solution": [
{
"name": "Strengthen effective, inclusive and accountable governance",
"id": "2"
}
],
"donor": [
"Australian DFAT",
"GLOBAL FUND TO FIGHT AIDS, TUBERCULOSIS",
"UNITED NATIONS DEVELOPMENT PRO"
],
"marker": [
"Hows",
"Joint Programme",
"Partner",
"Whos",
"COVID-19 Response"
]
},
{
],
"links": {
"next": null,
"previous": null
},
"count": 44
},
"status": 200,
"success": true
}
我嘗試了 data.data.map 但仍然面臨同樣的錯誤。我在這里做錯了什么?
uj5u.com熱心網友回復:
首先,你得到的 TypeError 是語法錯誤。箭頭函式的實作必須跟大括號
items.data.map((item) => (
<ol key = { item.data} >
Continents: {item.data[0]}
</ol>
))
至
items.data.map((item) => {
<ol key = { item.data} >
Continents: {item.data[0]}
</ol>
})
其次,items你要映射的是一個 JSON 物件的嵌套——鍵:值對。它不適合映射。
當用于從具有相同或相似結構的序列項中檢索資料時,映射迭代器或迭代陣列是完美的。
例如:
const arr = [{"id": "1", "name": "a"}, {"id": "2", "name": "b"}, {"id": "3", "name": "c"}];
arr.map((item) => {
console.log(item.id);
console.log(item.name);
})
您應該首先預處理您的資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505020.html
