首页 > 解决方案 > 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>
  );
}

……

标签: javascriptreactjsreduxreact-redux

解决方案


这是从父级传递数据的常见问题。为您的项目提供默认值:

function Product({ item, addItem }) {
  const { name, price, image } = item || {};

  ....

推荐阅读