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

求助排查TypeError: product.features.map is not a function错误

问题分析:TypeError: product.features.map is not a function

这个错误的核心是**product.features不是数组类型**——map()是数组专属方法,只有调用者为数组时才能正常执行。结合你提供的代码,可能的原因及解决方式如下:

可能的原因

  • product.features未定义或为null:组件初始化时,product可能还未完成异步加载(比如接口数据还没返回),或者接口返回的字段名与预期不符(比如实际是feature而非features),导致product.features为undefined或null。
  • product.features是其他非数组类型:接口返回的features可能是对象、字符串、数字等类型,而非数组,自然无法调用map()方法。

解决办法

1. 增加类型校验与兜底处理

在调用map()前先确认product.features是数组,用可选链和空数组兜底:

const [featureRatings, setFeatureRatings] = useState(() =>
  Array.isArray(product?.features) 
    ? product.features.map((feature: { category: any }) => ({
        category: feature.category,
        rating: 0,
      }))
    : []
);

2. 确保异步数据加载完成后再渲染

如果product是异步获取的,先判断product是否存在再执行逻辑:

if (!product) {
  return <div>加载中...</div>;
}

// 后续执行featureRatings的初始化逻辑

3. 检查数据源的字段正确性

确认接口返回的product对象中,features字段确实是数组类型,避免字段名拼写错误或数据格式不符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:46:01