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

React使用map渲染products数组报错TypeError: products.map is not a function

问题原因及解决方案

1. 组件参数未正确解构Props

React组件接收的参数是Props对象,不是直接传入的属性值。你的RetriveProducts和ProductList组件都把参数直接当成了目标值,导致拿到的不是数组或对应属性,这是触发map is not a function的核心原因。

修复RetriveProducts组件:

从Props对象中解构出products数组:

function RetriveProducts({ products }) { // 解构Props,拿到真正的数组
  return (
    <div>
      {products.map((product) => {
        return <ProductList
          image={product.image}
          name={product.name}
          price={product.price}
        />;
      })}
    </div>
  );
}

2. map回调函数未返回元素

你的map回调用了大括号{}但没有显式返回组件,导致map返回的是全为undefined的数组,既无法渲染,也会引发逻辑异常。

两种修复方式:

  • 方式1:添加return关键字
  • 方式2:去掉大括号,改用小括号()让箭头函数隐式返回(更简洁):
{products.map((product) => ( // 小括号代替大括号,自动返回组件
  <ProductList
    key={product.id} // 必须加唯一key,避免React渲染警告
    image={product.image}
    name={product.name}
    price={product.price}
  />
))}

3. ProductList组件未正确接收Props

同样,ProductList接收的是Props对象,不是单独的image、name、price参数,需要解构:

function ProductList({ image, name, price }) { // 解构Props拿到对应属性
  return (
    <div>
      <img src={image} alt={name} />
      <h2>{name}</h2>
      <span>{price}</span>
    </div>
  );
}

4. 列表渲染缺少key属性

React要求列表渲染时每个元素必须有唯一的key属性,这里直接用商品的id即可,避免渲染警告。

完整修复后的代码:

const products = [
  {
    id: 101,
    name: "Skirt",
    image: "https://i.pravatar.cc/48?u=118836",
    price: 700,
  },
  {
    id: 102,
    name: "Jeans",
    image: "https://i.pravatar.cc/48?u=933372",
    price: 1500,
  },
  {
    id: 103,
    name: "Top",
    image: "https://i.pravatar.cc/48?u=499476",
    price: 1000,
  },
];
function App() {
  return (
    <div className="App">
      <RetriveProducts products={products} />
    </div>
  );
}
function RetriveProducts({ products }) {
  return (
    <div>
      {products.map((product) => (
        <ProductList
          key={product.id}
          image={product.image}
          name={product.name}
          price={product.price}
        />
      ))}
    </div>
  );
}

function ProductList({ image, name, price }) {
  return (
    <div>
      <img src={image} alt={name} />
      <h2>{name}</h2>
      <span>{price}</span>
    </div>
  );
}
export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:22:45