[英]Uncaught TypeError: Cannot read properties of undefined (reading 'id')
I get undefined because item
from cartitems
is not undefined, how can I fix it?我未定义,因为
cartitems
中的item
未定义,我该如何解决?
1. 1.
import React,{useState} from 'react' import {products} from './data' function app() { const [cartitems, setCartitems] = useState([]) const onAddToCart = (product)=>{ const exist = cartitems.find((item)=> { return product.id == item.id }) if(exist){ setCartitems(cartitems.map((item)=>{ item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item })) } else{ setCartitems([...cartitems, {...product, qnty: 1}]) } } return ( <div> {products.map((product)=>( <div key={product.id}> <img src={product.image} style= {{width:"200px"}}/> <p>{product.name}</p> <button onClick={() => onAddToCart(product)}>Add To Cart</button> </div> ))} </div> ) } export default app
export const products = [ { id: '1', name: 'MacBook', price: 1400, image: 'https://picsum.photos/id/180/2400/1600', }, { id: '2', name: 'Old Car', price: 2400, image: 'https://picsum.photos/id/111/4400/2656', }, { id: '3', name: 'W Shoes', price: 1000, image: 'https://picsum.photos/id/21/3008/2008', }, ]
this can fix your issue:这可以解决您的问题:
1- you didnt return anything from map 1-你没有从地图返回任何东西
2- it's better to use function type in set state for cartitems 2-最好在设置状态下使用函数类型来处理caritems
function app() {
const [cartitems, setCartitems] = useState([])
const onAddToCart = (product)=>{
const exist = cartitems.find((item)=> {
return product.id == item.id
})
if(exist){
setCartitems(cartitems.map((item)=>
item.id == product.id ? ({...exist, qnty: exist.qnty + 1}): item
))
}
else{
setCartitems(s=>[...s, {...product, qnty: 1}])
}
}
In your initial render, you are trying to access a property that doesn't exist.在您的初始渲染中,您试图访问一个不存在的属性。 in other word, in your initial render, your
products
is an empty array换句话说,在您的初始渲染中,您的
products
是一个空数组
Use short circuting使用短路
{products &&
products.map((product) => (
<div key={product.id}>
<img src={product.image} style={{ width: "200px" }} />
<p>{product.name}</p>
<button onClick={() => onAddToCart(product)}>
Add To Cart
</button>
</div>
))}
The problem is: you don't return anything here in .map
.问题是:您没有在
.map
中返回任何内容。 That's why you are getting undefined
.这就是你得到
undefined
的原因。
setCartitems(cartitems.map((item)=>{
item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item
}))
Just remove {
and }
:只需删除
{
和}
:
setCartitems(cartitems.map((item)=>
item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item
))
Or add return
explicitly:或显式添加
return
:
cartitems.map(item => {
if (item.id == product.id) {
return { ...exist, qnty: exist.qnty + 1 }
}
return item
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.