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

77
Views
¿Cómo evito que keypress eventListner establezca mi variable de estado en verdadero y luego en falso?

Aquí está mi código.

 import { useState } from "react"; const App = () => { const [shout, setShout] = useState(true); const [message, setMessage] = useState("hello world!"); window.addEventListener("keypress", e => { console.log(shout); if(e.key === "a" && shout === true) { setMessage(message.toUpperCase()) } }); return ( <div> <h1>{message}</h1> <button onClick={() => setShout(!shout)}>disable keypress!</button> <button onClick={() => setMessage(message.toLowerCase())}>to lower case</button> </div> ) } export default App;

Cuando presiono el botón a en mi teclado, el mensaje se transforma en mayúsculas si no se hace clic en el botón de desactivación de keypress de teclas. Si se hace clic en presionar a tecla, el mensaje no debe estar en mayúsculas. Cuando console.log la variable shout en la devolución de llamada de eventListner , parece que la variable shout se establece de verdadero a falso simultáneamente. ¿Cómo puedo prevenirlo?

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

0

Debe usar useEffect para agregar efectos secundarios en reaccionar y también para asegurarse de que su oyente se elimine una vez que se desmonte el componente.

También prefiero el document en lugar de window , pero no creo que eso marque la diferencia.

 import { useState, useEffect } from "react"; const App = () => { const [shout, setShout] = useState(true); const [message, setMessage] = useState("hello world!"); useEffect(() => { const listener = (e) => { if(e.key === "a" && shout === true) { console.log(e.key, shout); setMessage(message.toUpperCase()); } }; document.addEventListener("keypress", listener); return () => { document.removeEventListener('keypress', listener); }; }, [shout, message]); return ( <div> <h1>{message}</h1> <button onClick={() => setShout(!shout)}>disable keypress!</button> <button onClick={() => setMessage(message.toLowerCase())}>to lower case</button> </div> ) } export default App;
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!