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

React使用map遍历数组渲染组件时props无法正常显示问题求解

React map遍历渲染子组件props不显示问题修复

存在的2处核心错误

  • map遍历传递props时,误将整个商品数组products传给了子组件的prod属性,而非当前遍历到的单个商品对象
  • 子组件直接将整个props对象命名为prod,没有正确获取到props下挂载的prod属性内容

修复代码

export const products = [
  {
    id: 1,
    title: "Chocotorta",
    desciption: "Torta de chocolate y dulce de leche",
    price: "$2,40",
    imgDesc: "",
    imgUrl: ""
  }
];

// 解构props获取传入的prod商品对象
const Item = ({ prod }) => {
  return (
    <>
      <Card>
        <CardImg alt={prod.imgDesc} src={prod.imgUrl} top width="100%" />
        <CardBody>
          <CardTitle tag="h5">{prod.title}</CardTitle>
          <CardSubtitle className="mb-2 text-muted" tag="h6">
            {prod.price}
          </CardSubtitle>
          <CardText>{prod.desciption}</CardText>
          <Button>Mostrar detalle</Button>
        </CardBody>
      </Card>
    </>
  );
};

return (
  <>
    {loading ? (
      <div style={spinnerStyle}>
        <Spinner color="primary" size="">
          .
        </Spinner>
      </div>
    ) : (
      // 传递当前遍历的单个商品,同时将key挂载到遍历的根组件Item上
      products.map((prod) => <Item key={prod.id} prod={prod} />)
    )}
  </>
);

额外说明

React中遍历渲染列表时,key属性需要挂载到map返回的第一个根元素上,不需要放到子组件内部的Card标签上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:54:05