Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
Decrement function in Reactjs doesn't work

I am using ReactJs and React-dom in 17.02 version.

I had the same problem described in this question: a value to increment and decrement using button. I used the solution proposed, changed my previous code.

From this one:

     handleDecrement = card => {
        let cards = [...this.state.cards];
        let id = cards.indexOf(card);
        cards[id] = {...card };
        cards[id].quantità --;
        this.setState({ cards });
      }

To this one:

     handleDecrement = card => {
        let cards = [...this.state.cards];
        let id = cards.indexOf(card);
        cards[id] = {...card };
        cards[id].quantità = card[id].quantità > 0 ? (card[id].quantità - 1) : 0;
        this.setState({ cards });
      }

But I see this error in the console TypeError: Cannot read properties of undefined (reading 'quantità') I know the meaning but I can't understand WHY I see this error if "quantità" (amount) is a prop set to zero:

    state = {
        cards: [
          {id:0, nome: 'California', prezzo: 1.99, immagine: california, quantità:0},
          {id:1, nome: 'Dragon', prezzo: 3.49, immagine: dragon, quantità:0},
          {id:2, nome: 'Dynamite', prezzo: 2.49, immagine: dynamite, quantità:0},
          {id:3, nome:'Philadelphia', prezzo:0.99, immagine: philadelphia, quantità:0},
          {id:4, nome:'Rainbow', prezzo:2.99, immagine: rainbow, quantità:0},
          {id:5, nome:'Shrimp', prezzo:1.49, immagine: shrimp, quantità:0}
        ]
      }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You didn't show where the reference to card comes from in handleDecrement, but somewhere the reference is changed so it won't work in indexOf. Instead, create a new list and avoid using mutation.

handleDecrement = card => {
  const cards = this.state.cards.map(c => c.id === card.id 
    ? {...c, quantità: Math.max(0, c.quantità - 1)} 
    : c);

  this.setState({ cards });
      }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda