类型错误:无法读取未定义的属性(读取‘图像’)
2021-09-15
1571
我在加载网页时出错。代码编译一切正常,但浏览器崩溃了。关注代码:
import {Card} from 'react-bootstrap'
function Product({ product }){
return(
<Card className="my-3 p-3 rounded">
<a href={'/product/${product._id}'}>
<Card.Img src={product.images}/>
</a>
<Card.Body>
<a href={'/product/${product._id'}>
<Card.Title as="div">
<strong>{product.name}</strong>
</Card.Title>
</a>
<Card.Text as="div">
<div className="my-3">
{product.rating} from {product.numReviews} reviews
</div>
</Card.Text>
</Card.Body>
</Card>
)
}
export default Product
关注错误:
5 | return(
6 | <Card className="my-3 p-3 rounded">
7 | <a href={'/product/${product._id}'}>
> 8 | <Card.Img src={product.images}/>
| ^ 9 | </a>
10 |
11 | <Card.Body>
TypeError: Cannot read properties of undefined (reading 'images')
有人知道可能发生了什么吗?我已经检查过我是否引用了错误的文件,但一开始一切都没问题
1个回答
我将添加一些条件,以确保组件加载时数据在这里。
像这样:
import {Card} from 'react-bootstrap'
function Product({ product }){
return(
<Card className="my-3 p-3 rounded">
<a href={'/product/${product._id}'}>
{Boolean(product?.images) && <Card.Img src={product.images}/>}
</a>
<Card.Body>
<a href={'/product/${product._id'}>
<Card.Title as="div">
<strong>{product.name}</strong>
</Card.Title>
</a>
<Card.Text as="div">
<div className="my-3">
{product.rating} from {product.numReviews} reviews
</div>
</Card.Text>
</Card.Body>
</Card>
)
}
export default Product
JSharles
2021-09-15