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

遍历数组trueDesc属性时触发TypeError错误求助

解决React中遍历数组属性时的"Cannot read properties of undefined (reading 'map')"错误

错误原因

你的cards数组里,第二个卡片对象(id: 2)没有定义trueDesc属性。当筛选到该卡片并尝试调用card.trueDesc.map()时,card.trueDesc是undefined,无法执行map方法,从而触发报错。

解决方案

方案1:给所有卡片补全trueDesc属性

直接为缺少该属性的卡片添加默认空数组,确保所有卡片都具备trueDesc:

const cards = [
  {
    id: 1,
    title: "tag1",
    tags: ["tag2"],
    price: 1050,
    num1: 4,
    num2: 4,
    pricesec1: 188,
    pricesec2: 200,
    trueDesc: [
      "firstdesc",
      "seconddesc",
      "thirddesc",
      "",
    ],
    time: 5,
  },
  { 
    id: 2, 
    title: "tag1", 
    tags: ["tag1"],
    trueDesc: [] // 添加默认空数组
  },
];

方案2:用可选链操作符安全调用map

渲染时通过?.判断属性是否存在,仅当card.trueDesc有效时才执行map:

<span className="plandesription">
  {card.trueDesc?.map((item) => (
    <>
      <AiOutlineCheck
        style={{
          color: "green",
          verticalAlign: "middle",
          marginLeft: "0.5rem",
        }}
      />
      <span>{item}</span>
    </>
  ))}
</span>

方案3:结合默认值确保始终有数组可遍历

通过||运算符给card.trueDesc设置默认空数组,避免因属性不存在导致报错:

<span className="plandesription">
  {(card.trueDesc || []).map((item) => (
    <>
      <AiOutlineCheck
        style={{
          color: "green",
          verticalAlign: "middle",
          marginLeft: "0.5rem",
        }}
      />
      <span>{item}</span>
    </>
  ))}
</span>

额外提醒

你的第二个卡片还缺少price、num1、num2等属性,渲染这些内容时同样会出现undefined问题,建议统一处理:

  • 可选链写法:{card?.price}
  • 默认值写法:{card.price || 0}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:53:12