Objetivo : Cada vez que presiono las teclas "W+C+N", aparece una imagen al azar en mi pantalla.
Resultado real : la imagen aparece solo cada dos pulsaciones de tecla. Por ejemplo, si presiono 4 veces en "W+C+N", solo aparecen 2 imágenes nuevas.
Mal uso de mi useEffect , viene de:
import egg from "./logo.png"; import { useState, useEffect } from "react"; function App() { let map = []; //array of keys to store const [coordinates, setcoordinates] = useState([]); //array of image coordinates const handleKey = (event) => { onkeydown = onkeyup = function (event) { map[event.keyCode] = event.type === "keydown"; }; //random image coordinates if (map[87] && map[67] && map[78]) { const newCoordinates = [...coordinates]; let random_left = Math.floor(Math.random() * window.innerWidth); let random_top = Math.floor(Math.random() * window.innerHeight); newCoordinates.push({ left: random_left, top: random_top }); setcoordinates(newCoordinates); } }; useEffect(() => { window.addEventListener("keypress", handleKey); return () => { window.removeEventListener("keypress", handleKey); }; }, [handleKey]); return ( <div className="App"> <img src={egg} alt="o easter egg" /> <h1>Rocambole</h1> <h2>Good luck!</h2> {console.log(coordinates)} {coordinates.map((item, index) => { return ( <img key={index} src={egg} alt="egg" className="newImg" style={{ top: `${item.top}px`, left: `${item.left}px` }} /> ); })} </div> ); } export default App;Intente actualizar el estado con una función, de esta manera se asegura de que el detector de eventos registrado en la memoria obtenga el estado nuevo cada vez, y también mueva la función handleKey dentro useEffect :
import egg from "./logo.png"; import { useState, useEffect } from "react"; function App() { let map = []; //array of keys to store const [coordinates, setcoordinates] = useState([]); //array of image coordinates useEffect(() => { const handleKey = (event) => { onkeydown = onkeyup = function (event) { map[event.keyCode] = event.type === "keydown"; }; //random image coordinates if (map[87] && map[67] && map[78]) { let random_left = Math.floor(Math.random() * window.innerWidth); let random_top = Math.floor(Math.random() * window.innerHeight); setcoordinates(coordinates =>[...coordinates, { left: random_left, top: random_top }]); } }; window.addEventListener("keypress", handleKey); return () => { window.removeEventListener("keypress", handleKey); }; }, []); return ( <div className="App"> <img src={egg} alt="o easter egg" /> <h1>Rocambole</h1> <h2>Good luck!</h2> {console.log(coordinates)} {coordinates.map((item, index) => { return ( <img key={index} src={egg} alt="egg" className="newImg" style={{ top: `${item.top}px`, left: `${item.left}px` }} /> ); })} </div> ); } export default App;