javascript - 类型错误: Cannot read properties of undefined (reading 'price' ) - Next. js 14.0.1

标签 javascript reactjs next.js

我不知道为什么它在Next.js中不起作用,但在其他模板中仍然可以正常工作。

let subTotal = 0

    if (selectedProducts?.length) {
        for (let id of selectedProducts) {
            const price = products.find(product => product.id === id).price
            subTotal += price
        }
    }

这是我的 GitHub 代码:e-commerce

我已经尝试了我所知道的一切,我需要帮助,tysm。

最佳答案

大概 products.find(product => Product.id === id) 在循环的至少一次迭代中没有返回对象。也许包括一些防御性编码以确保价格可用。

for (let id of selectedProducts) {

  // Get the object first
  const product = products.find(product => product.id === id);

  // If the product exists AND the price exists on the object
  // add it to the subtotal
  if (product?.price) subTotal += product.price;
}

例如:

const products = [
  { id: 1, name: 'potato', price: 2 },
  { id: 2, name: 'fish', price: 12 },
  { id: 3, name: 'gammon', price: 22 },
  { id: 4, name: 'radish', price: 1 }
];

const selectedProducts = [1, 3, 6];

let subtotal = 0;

for (const id of selectedProducts) {
  const product = products.find(product => product.id === id);
  if (product?.price) subtotal += product.price;
}

console.log(subtotal);

其他文档

关于javascript - 类型错误: Cannot read properties of undefined (reading 'price' ) - Next. js 14.0.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77462989/

相关文章:

javascript - 当草稿编辑器处于只读模式时 onChange 不会触发

javascript - ESLint 一致返回和嵌套回调

javascript - 如何更改滚动条上的导航栏 css 样式?

javascript - 在 ReactJS 呈现的内容中延迟加载图像、视频和 iframe

javascript - 如何在嵌套的 javascript 对象上使用扩展运算符?

javascript - React(next js) 类组件起作用。 Prop 怎么办?

reactjs - Next.js 中的 .env.local 文件设置不正确

javascript - 无法在 Next 中传递 props

javascript - HTML 作为输出 JQuery

javascript - React.js 'this' 的组件上下文