javascript - TypeError:无法读取未定义反应的属性“图像”
问题描述
这是我收到错误的地方,即 Product.js 这在我点击的产品上找到了 ID,来自 data.js 这里我收到标题中的错误我无法理解为什么它没有从 data.js 获取数据 请问有人可以帮我吗?
import React from 'react';
import data from '../data';
import { Link } from 'react-router-dom';
function Product(props) {
console.log(props.match.params.id);
const product = data.bags.find(x => x._id === props.match.params.id);
return <div>
<div className="back-to-result">
<Link to="/">Back to result</Link>
</div>
<div className="details">
<div className="details-image">
<img src={product.image} alt="product" /> // getting the error here
</div>
<div className="details-info">
<ul>
<li>
<h4>{product.brand}</h4>
</li>
<li>
{product.name}
</li>
<li>
{product.ratings} Stars ({product.reviews} Reviews)
</li>
<li>
Price: <b>₹{product.price}</b>
</li>
<li>
Description:
<div>
{product.description}
</div>
</li>
</ul>
</div>
<div className="details-action">
<ul>
<li>
Price: ₹{product.price}
</li>
<li>
Status: {product.status}
</li>
<li>
Qty: <select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</li>
<li>
<button className="button">Add to cart</button>
</li>
</ul>
</div>
</div>
</div>
}
export default Product;
从这里获取数据,即 data.js 实际上这是我存储数据的 redux 存储
export default {
bags: [
{
_id: '1',
category: 'watch',
name: "Bags",
brand: "Hublot",
price: 8000,
image: "/images/1.jpg",
ratings: 4.5,
reviews: 10
},
{
_id: '2',
category: 'bags',
name: "Watch",
brand: "Ulysse Nardin",
price: 10000,
image: "/images/2.jpg",
ratings: 3.5,
reviews: 12
},
{
_id: '3',
category: 'bags',
name: "Watch",
brand: "Tissot",
price: 4000,
image: "/images/3.jpg",
ratings: 5,
reviews: 24
},
{
_id: '4',
category: 'sunglasses',
name: "Watch",
brand: "Hublot",
price: 8000,
image: "/images/1.jpg",
ratings: 1.4,
reviews: 42
},
{
_id: '5',
category: 'bags',
name: "Watch",
brand: "Ulysse Nardin",
price: 10000,
image: "/images/2.jpg",
ratings: 3.7,
reviews: 14
},
{
_id: '6',
category: 'watch',
name: "Watch",
brand: "Tissot",
price: 4000,
image: "/images/3.jpg",
ratings: 4,
reviews: 17
}
]
}
解决方案
该行:
const product = data.bags.find(x => x.id === props.match.params.id);
可能导致product
存在undefined
。
如果是这种情况,您将无法访问您期望的任何字段,这会导致错误。
在该行之后, put if (!product) return <p>Product Not Found</p>
,如果产品未定义或为空,它将提前返回并且不会导致错误,但是已经找到产品然后它将继续并正常呈现。
此外,您的发现正在查看错误的字段名称。在您的数据片段中,项目具有_id
字段,而不是id
字段,您的查找应如下所示:
data.bags.find(x => x._id === props.match.params.id)
推荐阅读
- javascript - JS - mouseover 和 mouseout 事件是不稳定的
- javascript - Observable 不会在路由器更改时加载数据
- firebase - Vaadin Flow 中的 Firebase 身份验证
- angular - 将单例与数据一起用于段中
- python - 如何使用 event.type?
- python - For循环中的函数未返回正确的值
- r - 使用 lubridate 转换日期字符串,但不调整夏令时
- javascript - 更改纸张颜色 Material-UI
- javascript - 如何在 passport.js 中访问 req.user 数据成员
- excel - 如何选择所有值的范围,直到第 3 行下的末尾?