类型错误:无法解构“项目"的属性“名称",因为它未定义 [英] TypeError: Cannot destructure property 'name' of 'item' as it is undefined

查看:103
本文介绍了类型错误:无法解构“项目"的属性“名称",因为它未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

** 我无法弄清楚这里的问题.任何人都可以帮助我**当我将项目作为道具传递时,我得到了类型错误:无法解构项目"的属性名称",因为它未定义.

ProductsPage.js

<代码>...const ProductsPage = ({ products, currentUser }) =>{.....//注意:products 是一个包含产品对象的数组,每个产品都有 id、name、image 和 price返回 (<div className="products-page">......<div className="products-page__content">{filteredProducts.map((item) => (//我尝试使用 console.log(item) 并且我得到整个对象<产品密钥={item.id} item={item}/>))}

);};…………

Product.js

function Product({ item, addItem }) {const { 名称、价格、图像} = 项目;返回 (<文章类名=产品"><链接到=/产品/";className="product__searchbox"><BiSearch className="product__search-icon";/></链接><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", {风格:货币",货币:欧元",}).格式(价格)}</span>

<自定义按钮反转 onClick={() =>添加项目(项目)}>添加到购物车</自定义按钮></文章>);}

....

解决方案

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

function Product({ item, addItem }) {const { 名称、价格、图像 } = 项目 ||{};....

** I can't figure out the problem here. Can anyone help me please ** When I pass item as props I got TypeError: Cannot destructure 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>
  );
}

....

解决方案

This is a common issue where data is passed down from a parent. Provide a default for your item:

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

  ....

这篇关于类型错误:无法解构“项目"的属性“名称",因为它未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆