Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda