我不知道为什么它在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/