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

170
Views
dejar variable nula al pasar de padre a hijo | Reaccionar

Tengo una variable que no quiero vincular al estado en React. Así que lo declaré let con valor inicial nulo. Más tarde, con el evento, establezco su valor en el padre y luego lo paso al hijo. Pero en niño su valor se está volviendo nulo. No estoy seguro de qué error estoy cometiendo. A continuación se muestra el código.

 function Parent() { const[showChild, setShowChild] = useState(false); let data = null; const setData = () => { data = 'Test'; setShowChild(true); console.log('function called'); }; return ( <> <button onClick={setData}> Click Me </button> {showChild && <Child data={data} />} </> ); } function Child({data}) { console.log('data ' + data); return ( <> <h2> {data} </h2> </> ); } ReactDOM.render( <Parent />, document.getElementById('mountNode'), );
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Si desea conservar el estado, debe usar useState como lo hizo en la primera línea. entonces, en lugar de let data ... y const setData , debería tener algo como lo siguiente:

const [data, setData] = useState(null)

about 4 years ago · Juan Pablo Isaza Report

0

Debe usar useState , siempre que el estado cambie en el padre, el hijo se volverá a representar.

Cambié un poco su ejemplo para mostrarle qué sucede exactamente, el niño solo muestra el valor que envió el padre.

 const {useState} = React; const Parent=()=> { const[showChild, setShowChild] = useState(false); const[data, setData] = useState(0); //let data = null; const handleClick = () => { setData((prev=>prev+1)); setShowChild(true); console.log('function called'); }; return ( <div> <button onClick={handleClick}> Click Me </button> {showChild && <Child data={data} />} </div> ); } const Child=({data})=> { console.log('data ' + data); return ( <div> <h2> {data} </h2> </div> ); } ReactDOM.render( <Parent/> , document.getElementById("mountNode") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="mountNode"></div>

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!