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

241
Views
Reaccionar setState () no actualizar el estado

Estado

 state = { likedPosts: [{movie: '5b21ca3eeb7f6fbccd471816', down: true}], };

función

 handleLike(movieId) { if (this.state.likedPosts.filter((e) => e.movie === movieId).length > 0) { const likedPosts = this.state.likedPosts.filter(function (l) { if (l.movie !== movieId) { return l; } }); console.log(likedPosts); // this returns the expected object this.setState({ likedPosts }); // this not work } else { this.state.likedPosts.push({ movie: movieId, down: true }); // this works } console.log("now", this.state.likedPosts); }

Quiero enviar un nuevo objeto si el objeto no está en la matriz this.state.likedPosts o eliminar el objeto si ese objeto está en la matriz.

Cuando el objeto existe en this.state.likedPosts , console.log(likedPosts) devuelve la nueva matriz esperada. Pero this.setState({ likedPosts }) no actualiza el estado. ¿Cuál es el problema aquí?

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

0

Intenté agregar la función console.log("now", this.state.likedPosts); línea para verificar el estado después de actualizar al mismo tiempo. Por eso surge este problema.

 handleLike(movieId) { if (this.state.likedPosts.filter((e) => e.movie === movieId).length > 0) { const likedPosts = this.state.likedPosts.filter(function (l) { if (l.movie !== movieId) { return l; } }); console.log(likedPosts); // this returns the expected object this.setState({ likedPosts }); // this not work } else { this.state.likedPosts.push({ movie: movieId, down: true }); // this works } console.log("now", this.state.likedPosts); }

Aunque el estado se actualizó hasta que se completó la función, el estado anterior parecía estar allí.

Cuando se hace esto, el estado no se actualiza en la misma función, pero cuando se compara el estado usando otra función al mismo tiempo, parece estar funcionando correctamente.

about 4 years ago · Juan Pablo Isaza Report

0

Nunca debe modificar/mutar el estado directamente (this.state.something = something). Siempre debe usar el método setState.

Para hacer algo después de setState, debe usar el segundo argumento de setState.

 this.setState({ likedPosts }, () => { console.log(likedPosts) });

Además, te recomendaría que comiences a usar ganchos de reacción.

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!