Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
Cómo manejar un estado complicado en reaccionar

Antecedentes : soy un poco nuevo para reaccionar y lo estoy aprendiendo, he creado algunos sitios pero dudo mucho de mi forma de abordar el problema.

Entonces, mientras maneja un estado complejo. Por ejemplo, digamos que tenemos un carrito que tiene un producto que es un objeto y luego contiene una clave de cantidad. Ahora, ¿cómo podemos hacer cambios en esa cantidad? ¿Cuál será la mejor manera de hacerlo?

Ejemplo

 const [cart , setcart] = useState([ {_id: "1", name:"product1", quantity: 2 }, {_id: "2", name:"product2", quantity: 1 } ]);

digamos que necesitamos actualizar el recuento de cantidad del producto con la identificación 2 a 5. Cuál será el mejor enfoque, será mi forma de hacerlo.

 setcart((items)=>{ const changingItem = items.find((item)=>{return item.id === "2"}); changedItem.quantity = 5; const newCart = items; newCart.push(changingItem); return newCart; })

gracias

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

setCart(items => items.map(item => item.id === "2" ? {...item, quantity: 5} : item)}
about 4 years ago · Juan Pablo Isaza Report

0

Solo para notificar este caso de edición de un producto existente en la lista, si desea agregar productos, debe verificar si el artículo no existe, luego presione el nuevo producto en la matriz y devuelva una nueva referencia de la matriz.

 const [cart , setcart] = useState([ {_id: "1", name:"product1", quantity: 2 }, {_id: "2", name:"product2", quantity: 1 } ]); setcart((items)=> { // first you need to find the index of the target product. const itemIndex = items.find((item)=>{return item._id === "2"}); // check if the item exist. if (itemIndex !== -1 { // Then edit the same object inside the array. items[itemIndex].quantity = 5; } // Create new instance of items array. const newCart = [...items]; return newCart; })

about 4 years ago · Juan Pablo Isaza Report

0

setCart((items) => { const changingItem = items.find((item)=>{return item.id === "2"}); return [...items, {...changingItem, quantity: 5}] });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!