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

83
Views
React Too Many vuelve a generar un error al intentar cambiar el estado de una variable

No estoy seguro de por qué recibo este error, he estado buscando en línea para encontrar una respuesta, pero parece que no puedo resolverlo. El error proviene de cuando intento cambiar el estado de una variable de estado cuando se presiona la tecla 'Enter'. ¡Todavía soy nuevo para reaccionar, por lo que cualquier ayuda sería muy apreciada!

Aquí está el mensaje de error

 Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. 20 | 21 | case "Enter": 22 | if(timerState === false){ > 23 | setTimerState(true); | ^ 24 | } 25 | break; 26 |

aqui esta el archivo en cuestion

 import React, { useState, useEffect } from 'react'; import { words } from "./words.json"; import TypingTest from './components/TypingTest'; import SignInModal from './components/SignInModal'; import TitleBar from './components/TitleBar'; import Timer from './components/Timer'; import './App.css'; import { ThemeProvider } from 'styled-components'; function App() { const [index, setIndex] = useState(0); const [showSignIn, setShowSignIn] = useState(false); const [timerState, setTimerState] = useState(false); const onKeyPress = (event) => { console.log("Current key: ", event.key); switch (event.key) { case "Enter": if(timerState === false){ setTimerState(true); } break; case "Backspace": break; default: if(event.key === words[index]){ setIndex((index) => index + 1); } break; } }; const openSignIn = () => { setShowSignIn(prev => !prev); }; useEffect(() => { document.addEventListener('keydown', onKeyPress); return () => { document.removeEventListener('keydown', onKeyPress); }; }, [index]) return ( <div className="App"> <TitleBar openSignIn={openSignIn} /> <header className="App-header"> </header> <div className="landing"> {/* <Timer /> */} <TypingTest timerState={timerState} words={words} index={index}/> <button onClick = {() => setIndex(0)}>reset</button> <SignInModal showSignIn={showSignIn} setShowSignIn={setShowSignIn} /> </div> </div> ); } export default App;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

En primer lugar, debe desactivar su useEffect . Ocurre una sola vez. Puede acceder a su valor de estado actual dentro de setState

 setState(currentState => { return currentState; });

Los keydown , keypress y keyup hacen que el componente se vuelva a renderizar

Conozco una solución a este problema, pero no estoy seguro de que sea la solución principal, pero resuelve los problemas .

Puede definir sus estados inside useEffect como una variable y cambiar su valor

 useEffect(() => { let timerState; const onKeypress = (e) => { // do anything } document.addEventListener("keypress", onKeypress); return () => { document.removeEventListener("keypress", onKeypress); } }, []);
about 4 years ago · Juan Pablo Isaza Report

0

Agregar un oyente dentro de un useEffect que tiene dependencias significa que cada vez que cambian esas variables en la matriz de dependencia, está agregando otro oyente. Para configurar un oyente cuando se monta el componente, coloque el método addEventListener en un useEffect que tenga una matriz de dependencia vacía (o ninguna).

 useEffect(() => { document.addEventListener('keydown', onKeyPress); return () => { document.removeEventListener('keydown', onKeyPress); }; }, [])
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!