NextJS多层对象映射渲染问题:内层<ul>中map循环异常
NextJS多层对象映射渲染问题修复
问题场景
在NextJS中对多层结构的对象数组进行映射渲染时,第一层data.map可以正常渲染每个分组的标题,但<ul>内部的第二层循环无法正确渲染列表项。
错误原因
- 第二层循环错误遍历了整个
data数组,而非当前分组下的info子数组 - 文本取值路径错误:
word是info数组中的单个对象,直接访问word.text即可,无需word.info.text
修正后的代码
数据部分(保持不变)
const data = [ { title: "For Clients", info: [ { text: "How to hire"}, { text: "Talent Marketplace"}, { text: "Project Catalog"}, { text: "Talent Scout"}, { text: "Hire an Agency"}, { text: "Enterprise"}, { text: "Payroll Services"}, { text: "Direct Contracts"}, { text: "Hire Worldwide"}, { text: "Hire in the USA"}, ] }, { title: "For Talent", info: [ { text: "How to Find Work"}, { text: "Direct Contracts"}, { text: "Find Freelance Jobs Worldwide"}, { text: "Find Freelance Jobs in the USA"}, ] }, { title: "Resources", info: [ { text: "Help & Support"}, { text: "Success Stories"}, { text: "Upwork Reviews"}, { text: "Resources"}, { text: "Blog"}, { text: "Community"}, { text: "Affiliate Program"}, { text: "Free Business tools"}, ] }, { title: "Company", info: [ { text: "About Us"}, { text: "Leadership"}, { text: "Investor Relations"}, { text: "Careers"}, { text: "Our Impact"}, { text: "Press"}, { text: "Contact Us"}, { text: "Trust, Safety & Security"}, { text: "Modern Slavery Statement"}, ] }, ]
渲染部分(已修正)
{data.map((item, i) => ( <div className="item" key={i}> <div className="title flex justify-between" onClick={() => toggle(i)}> <h3>{item.title}</h3> <span>{selected === i ? "<" : ">"}</span> </div> <div className={selected === i ? "show" : "hide"}> <ul> {/* 修正:遍历当前item的info数组 */} {item.info.map((word, idx) => ( <li key={idx}> <p> <a href="#">{word.text}</a> </p> </li> ))} </ul> </div> </div> ))}
额外优化提示
- 给循环渲染的元素添加唯一
key属性(如示例中的key={i}和key={idx}),避免React警告,提升渲染性能 - 如果
info数组中的对象有唯一标识(如id),优先使用唯一标识作为key而非索引
内容的提问来源于stack exchange,提问作者Nicik
相关产品推荐
相关产品推荐

