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

React中多层嵌套数组map遍历渲染表格实现方法

代码问题排查

你的代码渲染不出内容有3个核心错误:

  • 箭头函数用{}包裹逻辑块时,没有显式return要渲染的JSX,两层map的返回值都是undefined,自然不会生成表格行
  • 字段取值路径错误:遍历外层items下的data数组时,拿到的单个item本身就是存储title/location等字段的对象,不需要额外加.data前缀,写item.title即可,你之前写的item.data.title取值为undefined
  • 列表项没有加唯一key属性,会触发React渲染警告,另外部分接口返回条目没有keywords字段,需要做空值兜底避免页面显示undefined
可直接运行的修复代码

把你原来的<tbody>部分替换为以下代码即可:

<tbody class="bg-white">
  {data?.collection?.items?.map((outerItem) => {
    return outerItem?.data?.map((item, idx) => {
      return (
        <tr class="whitespace-nowrap" key={item.nasa_id || idx}>
          <td class="px-6 py-4 text-sm text-gray-500">
            {item?.title || '-'}
          </td>
          <td class="px-6 py-4">
            <div class="text-sm text-gray-900">
              {item?.location || '-'}
            </div>
          </td>
          <td class="px-6 py-4">
            <div class="text-sm text-gray-500 max-w-xs truncate">
              {item?.description || '-'}
            </div>
          </td>
          <td class="px-6 py-4 text-sm text-gray-500">
            {Array.isArray(item?.keywords) ? item.keywords.join('、') : '-'}
          </td>
          <td class="px-6 py-4">
            <a
              href="#"
              class="px-4 py-1 text-sm text-white bg-blue-400 rounded"
            >
              Edit
            </a>
          </td>
          <td class="px-6 py-4">
            <a
              href="#"
              class="px-4 py-1 text-sm text-white bg-red-400 rounded"
            >
              Delete
            </a>
          </td>
        </tr>
      )
    })
  })}
</tbody>
优化建议

如果想让JSX逻辑更简洁,可以在拿到接口响应时先把嵌套数组扁平化,不用在渲染层写嵌套map:

// 接口请求回调里处理数据
axios.get("https://images-api.nasa.gov/search?media_type=image")
.then((response) => {
  const raw = response.data;
  // flatMap会自动把内层数组拍平成一维数组
  const formatData = raw?.collection?.items?.flatMap(listItem => listItem.data) || [];
  setData(formatData);
})

处理后渲染时直接遍历一维数组即可,代码更易维护:

<tbody class="bg-white">
  {data.map((item, idx) => (
    <tr class="whitespace-nowrap" key={item.nasa_id || idx}>
      {/* 表格行内容和之前一致 */}
    </tr>
  ))}
</tbody>

注:如果description内容过长,可以给对应单元格加截断样式,避免表格布局错乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 23:39:14