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

93
Views
Cómo pasar el estado más reciente de los padres a los componentes secundarios que son elementos del estado en React

Aquí, quise decir que padre e hijo fueran App() y Child() respectivamente en el código a continuación.

App() tiene un estado, myState , que es una matriz de Child() .
Cada Child() es básicamente un <button> con una determinada propiedad que contiene myState e imprime la id de cada Child() en myState en la consola cuando se presiona.

Lo que espero es que cuando se presiona Child() , se imprima el último myState .
Sin embargo, el myState realmente impreso parece la versión de cuando se aprobó, y no la última.

¿Hay alguna solución para hacer que la propiedad myState pase a Child() apunte al myState más reciente?

Habiendo agregado varios niños, puede verificar el myState de cada Child() en la consola presionándolos.
Por ejemplo, si presiona el botón ADD dos veces, aparecerán 2 botones adicionales.
Cuando se presiona Child() inicialmente agregado ( id of 'initial' ), imprime correctamente los id s, 1 y 2.
Sin embargo, cuando se presiona ID: 1 , no se imprime nada, y cuando se presiona ID: 2 , solo 1.

 import React, { useState } from 'react'; import './App.css'; function App() { const [myState, setMyState] = useState([] as JSX.Element[]); /* Below is a BAD state-passing example. setMyState makes myState point to an new array with another Child appended, although myState passed to the new Child references to the old array. Is there any way to pass the latest myState to Child??? */ function add() { setMyState([...myState, <Child key={myState.length + 1} id={myState.length + 1} myState={myState} />]); } return ( <div className="App"> <button onClick={add}>ADD</button> <Child key="initial" id="initial" myState={myState} /> {myState} </div> ); } function Child({ id, myState }: any): JSX.Element { return ( <div> <button id={id} onClick={() => { for (let child of myState as JSX.Element[]) { console.log(child.props.id); } }}>ID: {id}</button> </div> ); } export default App;
about 4 years ago · Juan Pablo Isaza
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!