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

React+TypeScript实现嵌套对象数组转表格的问题求助

问题分析与解决方案

原代码的核心问题

  1. DOM结构完全错误:你把所有数据项都塞进了同一个<tr>里,而且遍历item的所有键时,每个键都重复渲染request_date和invoice_number的单元格——比如当键是_id、container时,这些属性本身没有request_date,自然会渲染空单元格。
  2. 滥用类型断言:用any跳过TypeScript检查,既丢失了类型安全,也掩盖了数据访问的错误。

正确实现步骤

第一步:定义TypeScript类型(对应后端返回结构)

先给数据定义类型,避免瞎用any:

// 定义嵌套类型
interface Container {
  container_number: string;
  container_type: string;
  _id: string;
}

interface Importer {
  name: string;
  container: string;
  _id: string;
}

// 主数据类型
interface InvoiceItem {
  _id: string;
  request_date: string;
  invoice_number: string;
  container: Container;
  importers: Importer[];
}

第二步:正确渲染表格结构

每个item对应表格的一行,按需提取字段(包括嵌套对象和数组):

<table border={1}>
  {/* 表头 */}
  <thead>
    <tr>
      <th>申请日期</th>
      <th>发票编号</th>
      <th>集装箱编号</th>
      <th>集装箱类型</th>
      <th>进口商</th>
    </tr>
  </thead>
  {/* 表体 */}
  <tbody>
    {items?.map((item) => (
      <tr key={item._id}>
        {/* 处理日期格式(可选,把ISO字符串转成易读格式) */}
        <td>{new Date(item.request_date).toLocaleDateString()}</td>
        <td>{item.invoice_number}</td>
        {/* 访问嵌套对象的属性 */}
        <td>{item.container.container_number}</td>
        <td>{item.container.container_type}</td>
        {/* 处理数组:把进口商名字用逗号拼接 */}
        <td>{item.importers.map(imp => imp.name).join(', ')}</td>
      </tr>
    ))}
  </tbody>
</table>

关键说明

  • 每个item对应一个<tr>,用item._id作为key(React列表渲染要求的唯一标识)
  • 直接访问嵌套属性:item.container.container_number,因为已经定义了类型,TypeScript会自动做类型检查,不会出现访问不存在属性的问题
  • 数组处理:用map提取需要的字段,再用join转成字符串展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:15:15