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

107
Views
El estado es <cadena vacía> cuando se llama a la función en un evento clave

En React, tengo varios botones (imagine un diseño de PIN con números) que actualizan el estado al hacer clic. También agregué un detector de eventos al document por lo que al presionar las teclas del teclado también se actualiza el pin. Sin embargo, hay un problema extraño. Cuando agrego un número haciendo clic en un botón, el estado funciona correctamente y todo está bien, pero cuando presiono una tecla en un teclado físico, el estado se actualiza, ¡pero se registra como <empty string> !

Aquí está el código:

 export default function Keypad() { const [pin, setPin] = useState(""); function addNumber(num) { console.log(pin); // returns the correct pin with handleKeyClick, returns <empty string> with handleKeyDown if (pin.length < 6) { // only works if the pin is not <empty string> setPin((pin) => [...pin, num.toString()]); // works correctly with both handleKeyClick and handleKeyDown even if pin logged <empty string>! } } function handleKeyClick(num) { addNumber(num); } function handleKeyDown(e) { if (!isNaN(e.key)) { addNumber(e.key); } } useEffect(() => { document.addEventListener("keydown", handleKeyDown); return () => { document.removeEventListener("keydown", handleKeyDown); }; }, []); return ( <div> {/* just one button for example */} <button onClick={() => handleKeyClick(9)}>9</button> </div> ) }

Supongo que esto se debe a que el document no puede acceder al estado del pin , pero si fuera el caso, setPin tampoco debería funcionar. ¿Tengo razón?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Su componente no mantiene una referencia cuando escucha eventos DOM, esta respuesta tiene un código ordenado para escuchar eventos de ventana usando un gancho bastante simple. Cuando se aplica a su código, funciona como se esperaba:

 const {useState, useEffect, useRef} = React; // Hook function useEventListener(eventName, handler, element = window){ // Create a ref that stores handler const savedHandler = useRef(); // Update ref.current value if handler changes. // This allows our effect below to always get latest handler ... // ... without us needing to pass it in effect deps array ... // ... and potentially cause effect to re-run every render. useEffect(() => { savedHandler.current = handler; }, [handler]); useEffect( () => { // Make sure element supports addEventListener // On const isSupported = element && element.addEventListener; if (!isSupported) return; // Create event listener that calls handler function stored in ref const eventListener = event => savedHandler.current(event); // Add event listener element.addEventListener(eventName, eventListener); // Remove event listener on cleanup return () => { element.removeEventListener(eventName, eventListener); }; }, [eventName, element] // Re-run if eventName or element changes ); }; const Keypad = (props) => { const [pin, setPin] = useState([]); function addNumber(num) { console.log(pin); // returns the correct pin with handleKeyClick, returns <empty string> with handleKeyDown if (pin.length < 6) { // only works if the pin is not <empty string> setPin((pin) => [...pin, num.toString()]); // works correctly with both handleKeyClick and handleKeyDown even if pin logged <empty string>! } } function handleKeyClick(num) { addNumber(num); } function handleKeyDown(e) { if (!isNaN(e.key)) { addNumber(e.key); } } useEventListener("keydown", handleKeyDown) return ( <div> {/* just one button for example */} <button onClick={() => handleKeyClick(9)}>9</button> </div> ) return "Hello World" } ReactDOM.render(<Keypad />, document.getElementById("root"))
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

about 4 years ago · Santiago Trujillo 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!