简体   繁体   中英

Uncaught TypeError: Cannot read properties of undefined (reading 'id')

I get undefined because item from cartitems is not undefined, how can I fix it?

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

2- it's better to use function type in set state for cartitems

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}])

    }
  }

Problem

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

Solution

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 . That's why you are getting 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:

cartitems.map(item => {
    if (item.id == product.id) {
      return { ...exist, qnty: exist.qnty + 1 }
    }
    
    return item
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM