我正在尝试使用 React 显示来自 json 文件的数据,但我希望键值对中的列表也显示为列表。但是,我对是否需要映射我的道具或之后感到困惑。以下是我到目前为止所尝试的代码。
我想显示这个 json 文件中的主题列表:
[
{
"id": 145,
"title": "Middlemarch",
"authors": [
{
"name": "Eliot, George",
"birth_year": 1819,
"death_year": 1880
}
],
"translators": [],
"subjects": [
"Bildungsromans",
"City and town life -- Fiction",
"Didactic fiction",
"Domestic fiction",
"England -- Fiction",
"Love stories",
"Married people -- Fiction",
"Young women -- Fiction"
],
"bookshelves": ["Best Books Ever Listings", "Historical Fiction"],
"languages": ["en"],
"copyright": false,
"media_type": "Text",
"formats": {
"application/x-mobipocket-ebook": "https://www.gutenberg.org/ebooks/145.kf8.images",
"application/epub+zip": "https://www.gutenberg.org/ebooks/145.epub3.images",
"text/html": "https://www.gutenberg.org/ebooks/145.html.images",
"application/octet-stream": "https://www.gutenberg.org/files/145/145-0.zip",
"text/plain": "https://www.gutenberg.org/ebooks/145.txt.utf-8",
"image/jpeg": "https://www.gutenberg.org/cache/epub/145/pg145.cover.medium.jpg",
"text/plain; charset=us-ascii": "https://www.gutenberg.org/files/145/145-0.txt",
"application/rdf+xml": "https://www.gutenberg.org/ebooks/145.rdf"
},
"download_count": 165079
},
这是我一页的道具:
<Typography id="spring-modal-title" variant="h5" component="h2">
Title: {props.title}
</Typography>
<Typography id="spring-modal-title" variant="h5" component="h2">
Author: {props.author}
</Typography>
<Typography id="spring-modal-title" variant="h6" component="h2">
Language: {props.language}
</Typography>
<Typography id="spring-modal-description" sx={{ mt: 2 }}>
<ul>
Genre: {props.subjects}
</ul>
</Typography>
这就是我试图通过列表映射我的 json 文件中每个数组的地方:
<BookModal
title={book.title}
author={book.authors[0].name}
subjects={[book.subjects].map((s)=>(
<li>s</li>
))}
language={languageAbbr[book.languages]??book.languages}
description= {book.title}
/>
替换此代码:
<Typography id="spring-modal-description" sx={{ mt: 2 }}>
<ul>
Genre: {props.subjects}
</ul>
</Typography>
使用此代码:
<Typography id="spring-modal-description" sx={{ mt: 2 }}>
<ul>
Genres:
{props.subjects.map((subject, index) => (
<li key={index}>{subject}</li>
))}
</ul>
</Typography>
要将主题列表传递给 BookModal 组件,您可以直接传递 book.subjects 数组:
<BookModal
title={book.title}
author={book.authors[0].name}
subjects={book.subjects}
language={languageAbbr[book.languages] ?? book.languages}
description={book.title}
/>