简体   繁体   English

未捕获的类型错误:无法读取未定义的属性(读取“id”)

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

    }
  }

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换句话说,在您的初始渲染中,您的products是一个空数组

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 .问题是:您没有在.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.

相关问题 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id') - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id') 未捕获的类型错误:无法读取未定义的属性(读取“8”) - Uncaught TypeError: Cannot read properties of undefined (reading '8') 未捕获的类型错误:无法读取未定义的属性(读取“0”) - Uncaught TypeError: Cannot read properties of undefined (reading '0') 未捕获的类型错误:无法读取未定义的属性(读取“0”) - Uncaught TypeError: Cannot read properties of undefined (reading '0') 未捕获的类型错误:无法读取未定义的属性(读取“”) - Uncaught TypeError: Cannot read properties of undefined (reading '') “TypeError:无法读取未定义的属性(读取‘id’)” - "TypeError: Cannot read properties of undefined (reading 'id')" TypeError:无法读取未定义的属性(读取“_id”) - TypeError: Cannot read properties of undefined (reading '_id') 未捕获的类型错误:无法读取 null 的属性(正在读取“切片”)------ 未捕获的类型错误:无法读取未定义的属性(正在读取“过滤器”) - Uncaught TypeError: Cannot read properties of null (reading 'slice') ------ Uncaught TypeError: Cannot read properties of undefined (reading 'filter') Uncaught TypeError TypeError:无法读取未定义的属性(读取“路径”) - Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'path') 映射到 axios 响应的 _id 时未捕获类型错误:无法读取未定义的属性(读取“_id”) - while mapping into _id of axios response Uncaught TypeError: Cannot read properties of undefined (reading '_id')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM