【问题标题】:TypeError: Cannot read properties of undefined (reading '_id') cart addTypeError:无法读取未定义的属性(正在读取 \'_id\')购物车添加
【发布时间】:2022-09-24 01:46:44
【问题描述】:

有时当我尝试将 2 个元素添加到购物车时我遇到了这个问题,但是如果我刷新并尝试做同样的事情,这个错误不会出现:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading '_id')
context\StateContext.js (17:61) @ eval
  15 | 
  16 | const onAdd= (product, quantity) => {
> 17 |   const checkProductInCart = cartItems.find((item) => item._id === product._id );
     |                                                           ^
  18 |   
  19 |   setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity );
  20 |   setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity );.

【问题讨论】:

  • 请提供足够的代码,以便其他人可以更好地理解或重现该问题。

标签: javascript reactjs e-commerce


【解决方案1】:

嘿@Florin,获得有关您的环境的更多信息会非常有帮助。你是在 NextJS 之类的任何框架中运行 React,还是你的项目是 Create React App?这个错误与开发和生产环境一致吗?还有你的数据是从哪里来的? Redux、GraphQL,或者只是一个 fetch 或 axios 调用?

我对您帖子中问题的最佳猜测可能是在第一次渲染时,在数据从 API 或 Promise 返回之前有一个暂停,因此它的 null 或 undefined 一会儿,然后当您刷新它时,它正在从中获取数据缓存因此没有延迟。

也许在您的物品上添加一点检查可以解决问题?

我通常在我的代码中做这样的事情:

const checkProductInCart = cartItems && cartItems.find((item) => item._id === product._id );

这样迭代器find 除非cartItemstruthy(不是未定义或空)。

让我知道你的想法,如果这不起作用,也许有更多的细节,我可以给你更多的调试建议。

【讨论】:

    猜你喜欢
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2013-09-03
    • 2021-08-05
    • 2019-09-13
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多