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

React映射对象数组遇TypeError:无法读取cargoType属性

问题:渲染对象数组时触发TypeError,无法读取cargoType属性

报错信息

TypeError: Cannot read properties of undefined (reading 'cargoType')

尝试过的写法

  • 触发报错的写法:
const displayDashboard = bookings?.map((booking: BookingInterface, index) => (
    <Text key={index}>{Object.values(booking?.pallets[index].cargoType)}</Text>
));
  • 无返回内容的写法:
<Text key={index}>{booking.pallets.cargoType}</Text>
  • 触发报错的写法:
<Text key={index}>{booking.pallets[index].cargoType}</Text>
  • 返回索引字符串的写法:
<Text key={index}>{Object.values(booking?.pallets[index])}</Text>

数据结构示例(仅保留核心pallets部分)

// bookings数组的结构
[
  {
    pallets: [
      {cargoType: 'Engines & spare parts', stackable: false, ...},
      {cargoType: 'Furniture and accessories/Ceramics', stackable: false, ...},
      {cargoType: 'Engines & spare parts', stackable: false, ...},
      {cargoType: 'New Vehicles', stackable: false, ...},
      {cargoType: 'Industrial products', stackable: false, ...}
    ]
  },
  {
    pallets: [
      {cargoType: 'Chemicals & healthcare', stackable: false, ...},
      {cargoType: 'Old Vehicles', stackable: false, ...},
      {cargoType: 'Paperboard & prints', stackable: false, ...},
      {cargoType: 'Chemicals & healthcare', stackable: false, ...}
    ]
  }
]

诉求

原本期望通过booking.pallets.cargoType直接获取数据但无法渲染,确认是数据定位逻辑错误,寻求解决方法。


解决方案

问题核心是混淆了数组嵌套层级:每个booking的pallets本身是数组,不能直接通过booking.pallets.cargoType访问(数组没有该属性),且外层map的index是bookings数组的索引,和pallets数组的索引无关。

正确写法1:嵌套渲染所有cargoType

对每个booking的pallets数组做二次嵌套map:

const displayDashboard = bookings?.map((booking: BookingInterface, bookingIndex) => (
  <div key={bookingIndex}>
    {/* 可选:添加标题区分不同booking */}
    <h4>Booking {bookingIndex + 1}</h4>
    {booking.pallets?.map((pallet, palletIndex) => (
      <Text key={palletIndex}>{pallet.cargoType}</Text>
    ))}
  </div>
));

正确写法2:合并同个booking下的cargoType

如果需要将同一个booking的所有cargoType合并为字符串展示:

const displayDashboard = bookings?.map((booking: BookingInterface, bookingIndex) => (
  <Text key={bookingIndex}>
    {booking.pallets?.map(pallet => pallet.cargoType).join(', ')}
  </Text>
));

关键说明

  • 外层map遍历bookings数组,每个元素是单个booking对象
  • 内层map遍历当前booking的pallets数组,每个元素是包含cargoType的对象
  • 用可选链?.处理pallets可能为undefined的情况,避免触发报错
  • 不要复用外层index作为内层数组的索引,二者属于不同层级,无关联

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:10:28