【问题标题】:Array findIndex() function - Cannot read property 'id' of undefined数组 findIndex() 函数 - 无法读取未定义的属性“id”
【发布时间】:2017-08-29 17:44:54
【问题描述】:

我正在尝试在 Angular2 中实现 addtoCart 功能。 我正在使用 typescript 类来表示 LineItem,它表示产品以及数量和总价(数量 * 产品价格)。

export interface Product {
  id?: number;
  name?: string;
  price?: number;
}

订单项:

export class LineItem {
  product: Product;
  quantity: number;
  totalPrice: number;
}

订单项数组:

lineItems: LineItem[];

在添加到购物车功能中,我想检查该项目是否已添加,如果是,则只需找到与该产品对应的订单项并更新该特定订单项。

我选择的方法是: - 找到索引。 - 如果 >-1 则添加新的行项目。 - 否则编辑订单项。

问题是:当我尝试查找索引时,它显示此错误

Cannot read property 'id' of undefined

代码是:

  addProductToCart(product: any, quantity: number) {
    const lineItem: LineItem = Object.assign({}, product);
    lineItem.quantity = quantity;
    lineItem.totalPrice = product.price * quantity;
    const index = this.lineItems.findIndex( (item) => {
       return item.product.id === product.id
    });
    if(index > -1) {
      // edit the current item .
      this.lineItems[index].quantity = quantity;
      this.lineItems[index].totalPrice = quantity * product.price;

    }else {
      this.lineItems.push(lineItem);
    }
  }

第一次调用没有错误,第二次调用抛出错误。 这是问题所在:

  const index = this.lineItems.findIndex( (item) => {
       return item.product.id === product.id
    });

item.product.id 抛出:无法读取未定义的属性“id”。

是否有打字稿类或接口或任何逻辑错误。

【问题讨论】:

  • 你确定不是product.id在扔吗?那是在同一条线上。您是否记录了itemitem.productproduct 的值以查看其中的内容?这似乎是调试时要尝试的第一件事。我们没有您的任何数据,因此很难判断。
  • 在控制台中记录你的 lineItems,看看你会得到什么。

标签: javascript angular


【解决方案1】:
const lineItem: LineItem = Object.assign({}, product);

这行结果是一个普通的对象:

lineItem = {ProductID: 1, ProductName: "Chai", UnitPrice: 18, quantity: 2}

所以没有 item.product.id 对象链它的简单普通对象

PLUNKER

【讨论】:

  • lineItem 的类型是 LineItem,而不是 Product。而且产品不是数组,所以这基本上是错误的:this.lineItems.product.push(lineItem);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
  • 2021-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多