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

React报错TypeError: Cannot read properties of undefined (reading 'name')如何解决

问题原因

报错的核心原因是你在Products.jsx中遍历产品数组渲染Product子组件时,没有将遍历得到的单条产品数据作为prop传递给Product组件。此时Product组件中解构得到的product参数为undefined,尝试读取undefined.name就会触发该类型错误。

修复方案

修改Products.jsx中调用Product组件的代码,传入product prop即可:

{products.map((product) => (
  <Grid item key={product.id} xs={12} sm={6} md={4} lg={3}>
    {/* 新增product属性传入数据 */}
    <Product product={product} />
  </Grid>
))}

可选优化

你也可以在Product组件中使用可选链语法,避免后续因为数据异常触发同类报错:

// 例如将product.name替换为product?.name
<CardMedia className={classes.media} image="" title={product?.name} />
<Typography variant="h5" gutterBottom>
  {product?.name}
</Typography>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:36:04