React/Javascript嵌套数组映射问题:内层map无法渲染排查
React中嵌套数组无法渲染的问题
问题描述
我正在学习如何在React/Javascript中渲染包含嵌套数组的数据,以下是我的数据结构示例:
{ id: Math.floor(Math.random() * 100000), date: moment() .add(Math.floor(Math.random() * 100), "days") .calendar(), title: "someTitle", people: [ { id: Math.floor(Math.random() * 100000), name: "someName", photo: "somePhotos", level: "someLevel", }, { id: Math.floor(Math.random() * 100000), name: "someName", photo: "somePhotos", level: "someLevel", }, { id: Math.floor(Math.random() * 100000), name: "someName", photo: "somePhotos", level: "someLevel", }, ], }
我尝试编写代码渲染该数据,但遇到了问题,我的代码如下:
{someList?.map((item, i) => ( <div className="flex-none bg-white rounded-xl shadow-xl w-[20rem] ml-4 px-6 py-6"> <h1 className="text-[1.5rem] font-bold leading-none"> {item.title} </h1> <h1>{item.date}</h1> <div className="h-1.5 bg-gray-200 rounded-full my-2"></div> <h1 className="font-bold">someLevel</h1> {item.people?.map((people, i) => { <div className="border-[#DCDCDC] border-2 px-4 py-2 rounded-xl flex"> <div className="w-12 bg-red-400 h-12 rounded-full mr-2"></div> <div className="flex-auto bg-blue-600"> <b>{people.name}</b> </div> </div>; })} </div> ))}
目前的问题是,item.title和item.date可以正常显示,但嵌套在someList映射中的内层map无法渲染内容,请问我是不是哪里写错了?
问题原因与解决方案
你的内层map函数没有返回JSX元素,这是核心问题:
- 当箭头函数使用
{}包裹函数体时,必须显式使用return语句返回内容; - 你当前的代码只是在函数体内写了JSX,但没有返回它,所以React无法渲染这部分内容。
另外,React列表渲染时需要给每个子元素添加唯一的key属性,避免控制台警告,建议使用数据中的id而不是索引i作为key。
修正后的代码
{someList?.map((item) => ( <div key={item.id} className="flex-none bg-white rounded-xl shadow-xl w-[20rem] ml-4 px-6 py-6"> <h1 className="text-[1.5rem] font-bold leading-none"> {item.title} </h1> <h1>{item.date}</h1> <div className="h-1.5 bg-gray-200 rounded-full my-2"></div> <h1 className="font-bold">someLevel</h1> {/* 方案1:显式return */} {item.people?.map((person) => { return ( <div key={person.id} className="border-[#DCDCDC] border-2 px-4 py-2 rounded-xl flex"> <div className="w-12 bg-red-400 h-12 rounded-full mr-2"></div> <div className="flex-auto bg-blue-600"> <b>{person.name}</b> </div> </div> ); })} {/* 方案2:用小括号()实现隐式返回,更简洁 */} {item.people?.map((person) => ( <div key={person.id} className="border-[#DCDCDC] border-2 px-4 py-2 rounded-xl flex"> <div className="w-12 bg-red-400 h-12 rounded-full mr-2"></div> <div className="flex-auto bg-blue-600"> <b>{person.name}</b> </div> </div> ))} </div> ))}
关键修正点
- 内层
map函数添加了return(方案1),或者改用小括号包裹JSX实现隐式返回(方案2); - 给外层和内层的列表元素都添加了基于
id的key属性; - 把变量名
people改成person(可选,但更符合单个元素的语义)。
内容的提问来源于stack exchange,提问作者Haksatrya Bhaswara
相关产品推荐
相关产品推荐

