我正在尝试使用 React 创建一个侧边栏。此侧边栏将显示帖子的标题,后跟标题和副标题列表(格式为 [标题] [子标题]、[标题2] [子标题2] 等...)。数据采用字典的形式。但是我无法找到如何使用映射函数来迭代字典中的特定键。
这是我所拥有的:
import React, {useState} from 'react'
import {DUMMY_POSTS} from '../data'
import Thumbnail1 from '../images/1.png'
const DUMMY_POST = [
{
id: '1',
thumbnail: Thumbnail1,
category:'NPO',
title:'1971',
headers:['Logo','Colors','Typography','Graphical Elements','Applications'],
sub_headers:[[''],
['Main Colors','Space Neutrals','Heading'],
[''],
[''],
['Postcards','Accreditations','Ticket Packaging','Event Schedule']],
}]
const PostDetail = () => {
const [postDetails,setPostDetails] = useState(DUMMY_POST)
return (
<section className='PostDetails'>
<div className="details__sidebar">
{postDetails.map(({id,title}) => {
return <div className="details__sidebar__container">
<div className='details__sidebar__title'>
<h3>{title}</h3>
</div>
</div> })}
{postDetails.map(({headers,sub_headers}, index) => {
return<div className="details__sidebar__headers" key = {index}>
<ul><h4>{headers[index]}</h4> </ul>
<div className="details__sidebar__sub-headers">
<p>{sub_headers[index]}</p>
</div>
</div>
})}
<div className='Post__Details'>
Post Details
</div>
</div>
</section>
)
}
export default PostDetail
但是,这会创建一个仅包含第一个标头和第一个 sub_header 数组的列表
总之,这是我试图用伪代码做的事情:
Create an h3 element containing the postDetail's title
For each header in postDetail's headers:
Create a div with key as the index
Create an h4 element containing the current header
If the length of the corresponding sub_headers array is greater than 0:
Create a ul element
For each subHeader in the corresponding sub_headers array:
Create an li element containing the current subHeader
我根据你的伪代码写了一个返回语句。这里的主要要点是我有一个嵌套在 postDetail 的映射函数中的映射函数来迭代标题。您的第二个映射调用是迭代 postDetails 数组并使用该数组中的索引,而不是 headers 数组中的索引。由于 postDetails 长度为 1,因此无论有多少个标头,索引都不是来自标头数组。
{
postDetails.map(detail => {
return (
{/* Create an h3 element containing the postDetail's title */}
<h3>{detail.title}</h3>
{/* For each header in postDetail's headers: */}
{detail.headers.map((header, index) => {
return (
{/* Create a div with key as the index */}
<div key={index}>
{/* Create an h4 element containing the current header */}
<h4>{header}</h4>
{/* If the length of the corresponding sub_headers array is greater than 0: */}
{(detail.sub_headers[index].length > 0) &&
{/* Create a ul element */}
<ul>
{/* For each subHeader in the corresponding sub_headers array: */}
{detail.sub_headers[index].map(subHeader => {
return (
{/* Create an li element containing the current subHeader */}
<li>{subHeader}</li>
)
})
</ul>
}
</div>
)
})
)
})
}