[英]Iterating json data from an Api
I have an api from which I want to display the data, I have 2 arrays I think each one has category
how would I iterate and display these 2 categories, so category Arts
and category Entertainment
.I would really appreciate the help.我有一个 api 我想从中显示数据,我有 2 个 arrays 我认为每个都有category
我将如何迭代和显示这两个类别,所以类别Arts
和类别Entertainment
。我真的很感激帮助。 Thanks in advance提前致谢
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 books = await response.json()
console.log(books)
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"
}]
]
I can't comment because I don't have enough reputation, but it looks like you're using map wrong.我无法发表评论,因为我没有足够的声誉,但看起来你使用 map 错误。
Array.prototype.map's callback takes in currentValue
, index
, and array
Array.prototype.map as arguments. Array.prototype.map 的回调接受currentValue
、 index
和array
Array.prototype.map为 arguments。 You can get the id
, and category
from the currentValue
by destructuring (notice the curly brackets):您可以通过解构从currentValue
中获取id
和category
(注意大括号):
//...
books[0].map(({id, category}) => {
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.