javascript - TypeError:无法解构“项目”的属性“名称”,因为它未定义
问题描述
** 我无法解决这里的问题。任何人都可以帮助我 ** 当我将项目作为道具传递时,我得到 TypeError: Cannot destructure property 'name' of 'item' 因为它是未定义的。
ProductsPage.js
...
const ProductsPage = ({ products, currentUser }) => {
.....
// note: products is an array with objects of product each product has id, name, image and price
return (
<div className="products-page">
....
..
<div className="products-page__content">
{filteredProducts.map((item) => ( // I try to console.log(item) and I get whole object
<Product key={item.id} item={item} />
))}
</div>
</div>
);
};
........
产品.js
function Product({ item, addItem }) {
const { name, price, image } = item;
return (
<article className="product">
<Link to="/products/" className="product__searchbox">
<BiSearch className="product__search-icon" />
</Link>
<img src={image} alt={name} className="product__img" />
<div className="product__footer">
<h4 className="product__title">{name}</h4>
<span className="product__price">
{new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
}).format(price)}
</span>
</div>
<CustomButton inverted onClick={() => addItem(item)}>
Add to Cart
</CustomButton>
</article>
);
}
……
解决方案
这是从父级传递数据的常见问题。为您的项目提供默认值:
function Product({ item, addItem }) {
const { name, price, image } = item || {};
....
推荐阅读
- python - pandas.setindex() 到日期时间的问题
- perl - Perl“使用未初始化的值”
- ios - 快速从 API 调用传递 json 数组的所有成员
- angularjs - 带有 templateUrl 业力错误的指令
- python - Itertools 组合/排列大小
- android - 如何将带有片段的 ViewPager 添加到 Android 中的 EditText 自动完成建议视图?
- aurelia - Aurelia 动画未启动
- vmware-workstation - 在带有 GPU 的 Windows 10 VMWare 主机上运行 Linux 来宾
- javascript - 多个带有 flickity 灯箱的画廊
- php - 在 laravel 中查看共享所有设置表是一种好习惯吗?