【问题标题】:TypeError: Cannot destructure property 'name' of 'item' as it is undefinedTypeError:无法解构“项目”的属性“名称”,因为它未定义
【发布时间】:2021-02-10 19:16:49
【问题描述】:

** 我无法解决这里的问题。谁能帮助我请** 当我将 item 作为 props 传递时,我得到 TypeError: Cannot destruct property 'name' of 'item' as it is undefined.

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>
  );
};

........

Product.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>
  );
}

....

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      Item 未定义,它不在提供给 Product() 的对象中。因此,当您尝试从项目中获取名称时,js 会阻塞并给您该错误。

      试试这个代码:

      const myCoolThing = {foo: {cats: 11};
      const { foo } = myCoolThing;
      const { cats } = foo;
      console.log(cats);
      
      const { bar } = myCoolThing;
      const { dogs } = bar; // Look! It's your error.
      console.log(dogs);
      

      在您的情况下,您正在遍历过滤后的产品列表。很可能列表中至少有一个元素是undefined。过滤的过程很可能是把索引设置为undefined,而不是拼接数组去掉索引。

      【讨论】:

      • 它有帮助。感谢分享这个;)
      【解决方案3】:

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

      function Product({ item, addItem }) { const { 名称、价格、图像 } = 项目 || {}; 这对我有用

      【讨论】:

      • 此答案是现有答案的副本
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-20
      • 2020-10-07
      • 2021-10-20
      • 2021-11-13
      • 1970-01-01
      • 2021-03-08
      • 2021-05-11
      相关资源
      最近更新 更多