循环获取来自 Api 的数据
2021-03-17
66
我有一个 api,我想从中显示数据,我有 2 个数组,每个数组都有一个类别,我将如何迭代并显示这两个类别,即艺术类别和娱乐类别。我尝试了一些方法,但没有奏效,它给出了这个错误
TypeError:无法读取未定义的属性“map”
,非常感谢您的帮助。提前致谢
import React,{useState, useEffect} from 'react'
import './Home.css'
import Books from './Books'
const url="https://json-api-smaiil.herokuapp.com/books"
const Home = () => {
const [loading, setLoading] = useState(true)
const [books, setBooks] = useState({})
const fetchData =async()=>{
setLoading(true)
const response = await fetch(url)
const data = await response.json()
console.log(data)
setBooks(books)
}
useEffect(()=>{
fetchData();
})
return (
<div>
<h1 className='categories'>Categories</h1>
{books[0].map((book)=>{
return (<li key={book.id}>{book.category}</li>)
})}
</div>
)
}
export default Home
{
"Arts":[{
"category": "Arts"
Language: "English"
Narrated by: "Faith G. Harper PhD LPC-S ACS ACN"
Regular price: "$17.47"
Release date: "03-20-18"
bookName: "Unf--k Your Brain"
by: "Faith G. Harper PhD LPC-S ACS ACN"
category: "Arts and Entertainment"
id: "1"
},
{
Language: "English"
Length: "1 hr and 33 mins"
Narreted by: "James Taylor"
Regular price: "$9.95"
Release date: "01-31-20"
Series: "Words + Music"
bookName: " Break Shot: My First 21 Years"
by: "James Taylor"
id: "2"
}],
"Entertainment":[{
"category" :"Entertainment"
"id": "9",
"image": "https://m.media-amazon.com/images/I/51tpSb0iy+L._SL500_.jpg",
"bookName": "The Hiding Place",
"by": "Corrie ten Boom, John Sherrill, Elizabeth Sherrill",
"Narreted by": "Wanda McCaddon",
"Length": "8 hrs and 14 mins",
"Release date": "10-03-11",
"Language": "English",
"rating": "6,641 ratings",
"Regular price": "$24.95",
},
{
Language: "English"
Length: "1 hr and 7 mins"
Narreted by: "Aidan Gillen"
Regular price: "$9.95"
Release date: "03-31-15"
bookName: "The Art of War"
by: "Sun Tzu"
id: "12"
rating: "19,765 ratings"
}]
}
3个回答
更改此项。因为您必须映射对象,而不是数组。
books[0].map((book)=>{
return (<li key={book.id}>{book.category}</li>)
})
至
Object.keys(books).map(function(key, index) {
let book = books[key];
return <li key={key}>{book[0].category}</li>
});
Jakir Hossen
2021-03-17
尝试以下代码:
books.Arts.map((book)=>{
return (<li key={book.id}>{book.category}</li>)
})
我发现的一个问题是数组索引 1 处的条目没有与类别相对应的键值,这会给您带来不理想的结果。
navintellis
2021-03-17
const [books, setBooks] = useState({})
在此行中,您将默认值设置为 Object ,您之所以收到该错误,是因为 map 函数不适用于对象。将默认值更改为 空数组 。
const [books, setBooks] = useState([])
Kenny Sexton
2021-03-17