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?
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>