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

198
Views
Cómo insertar en matriz y setState para múltiples propiedades en un bucle

Quiero establecer una matriz múltiple mientras inserto elementos en la matriz. ¿Alguien puede sugerirme cuál es el problema con el código?

 import React from "react"; import { render } from "react-dom"; class App extends React.Component { constructor() { super(); this.state = { aArr: [], bArr: [], cArr: [] }; this.someFunction(); } someFunction() { let result = [ { a: 1, b: 2, c: 3 }, { a: 4, b: 5, c: 6 } ]; result.forEach((item) => { this.setState({ aArr: [...this.state.aArr, item.a], bArr: [...this.state.bArr, item.b], cArr: [...this.state.cArr, item.c] }); }); } render() { return ( <div> aArr: {this.state.aArr} bArr: {this.state.bArr} </div> ); } } render(<App />, document.getElementById("root"));

la salida final debe ser aArr : 1,4 bArr : 2,5

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

0

Está intentando establecer el estado en un bucle forEach. Sin embargo, this.setState() es asíncrono y lleva algún tiempo ejecutarlo. Por lo tanto, no puede configurar datos en el estado. Debe actualizar su resultado en alguna otra variable, luego puede configurar esos datos en su estado. Así es como puedes hacerlo-

 class App extends React.Component { constructor() { super(); this.state = { aArr: [], bArr: [], cArr: [] }; let result = [ { a: 1, b: 2, c: 3 }, { a: 4, b: 5, c: 6 } ]; const {aArr, bArr, cArr} = this.state result.map(res => { aArr.push(res.a) bArr.push(res.b) cArr.push(res.c) }) this.setState({aArr, bArr, cArr}); } render() { return <div>aArr: {this.state.aArr.join(', ')} <br/> bArr: {this.state.bArr.join(', ')}</div>; } }

Puede encontrar el código de trabajo aquí

about 4 years ago · Juan Pablo Isaza Report

0

useReducer suele ser preferible a useState cuando tiene una lógica de estado compleja que involucra múltiples subvalores o cuando el siguiente estado depende del anterior.

https://reactjs.org/docs/hooks-reference.html#usereducer

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!