You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React组件中动态渲染含多对象的嵌套数组?

在React中动态渲染嵌套数组的解决方案

嘿,我来帮你搞定这个问题!你当前的代码只遍历了obj[0](也就是第一个子数组),所以自然看不到其他子数组的内容。要渲染整个嵌套结构,我们需要嵌套使用两次map遍历——先处理外层的每个子数组,再处理子数组里的每个对象。

你的问题重现

先确认下你的数据源和尝试过的代码:

数据源示例:

const obj = [
  [
    { name: "Test 1", category: "Test 1" },
    { name: "Test 2", category: "Test 1" },
  ],
  [
    { name: "Test 1", category: "Test 2" },
    { name: "Test 2", category: "Test 2" },
  ]
]

你尝试的代码(仅渲染第一个子数组):

list = obj[0].map((e, index) => {
  return (
    <div key={index}>
      <p>{e.name}</p>
      <h6>{e.category}</h6>
    </div>
  )
})
return (
  <div>
    {list}
  </div>
)

正确的实现方式

我们通过两层map来遍历整个嵌套数组,外层遍历每个子数组,内层遍历子数组中的每个对象。另外还要注意key的合理性(尽量不用index当key,除非数组完全静态):

function NestedList() {
  const obj = [
    [
      { name: "Test 1", category: "Test 1" },
      { name: "Test 2", category: "Test 1" },
    ],
    [
      { name: "Test 1", category: "Test 2" },
      { name: "Test 2", category: "Test 2" },
    ]
  ];

  return (
    <div className="nested-list-container">
      {/* 第一层map:遍历外层的每个子数组 */}
      {obj.map((subArray, subArrIndex) => (
        {/* 给每个子数组加个容器,方便样式区分 */}
        <div key={`sub-group-${subArrIndex}`} className="sub-group">
          {/* 第二层map:遍历子数组里的每个对象 */}
          {subArray.map((item, itemIndex) => (
            <div key={`item-${subArrIndex}-${itemIndex}`} className="item-card">
              <p>{item.name}</p>
              <h6>{item.category}</h6>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

额外优化建议

  1. 关于key的最佳实践:如果你的对象有唯一标识(比如id字段),优先用这个标识作为key,比如key={item.id},这样React在更新数组时能更高效地识别元素变化,避免不必要的重渲染。
  2. 分组标题优化:如果每个子数组的category是统一的,你可以给每个子数组添加一个分组标题,让界面更清晰:
{obj.map((subArray, subArrIndex) => (
  <div key={`sub-group-${subArrIndex}`} className="sub-group">
    {/* 用子数组第一个元素的category作为分组标题 */}
    <h3 className="group-title">{subArray[0]?.category}</h3>
    {subArray.map((item) => (
      <div key={item.name} className="item-card">
        <p>{item.name}</p>
      </div>
    ))}
  </div>
))}

内容的提问来源于stack exchange,提问作者Sultan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:22:41