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

92
Views
La variable React State sigue restableciéndose y cambiando dentro de un render

 export default function Questionnaire(props) { const initialState = { questionCount: 0, is_host: false } const [ roomData, setRoomData ] = useState(initialState) const { roomCode } = useParams() const [ displayedTable, setDisplayedTable ] = useState(1); useEffect(() => { fetch("/audio/get-room" + "?code=" + roomCode) .then(res => res.json()) .then(data => { setRoomData({ roomData, questionCount: data.questionCount, is_host: data.is_host, }) }) window.addEventListener('keydown', (e) => { console.log("questionCount 1:", roomData.questionCount); if (e.keyCode == '39') { setDisplayedTable(showNextStage(displayedTable, roomData.questionCount)); } else if (e.keyCode == '37') { setDisplayedTable(showPreviousStage(displayedTable)); } }); // cleanup this component return () => { window.removeEventListener('keydown', (e) => { if (e.keyCode == '39') { setDisplayedTable(showNextStage(displayedTable, roomData.questionCount)); } else if (e.keyCode == '37') { setDisplayedTable(showPreviousStage(displayedTable)); } }); }; },[roomCode,setRoomData]) console.log("questionCount 2:", roomData.questionCount); return ( <div> {components[displayedTable]} </div> ) }

Cada vez que State se actualiza, los dos console.logs() devuelven "questionCount 1: 0" y "questionCount 2: 5" (el valor que recupera fetch()). Pero dado que questionCount solo se establece en 0 en el UseState() inicial, no debería restablecerse en 0 y debería permanecer en 5 después de que se establezca en eso. Pero no es así. ¿Por qué es esto? ¿Cómo es posible que la variable State tenga dos valores diferentes en el render(), cuando los cambios de estado están destinados a volver a renderizar la página?

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!