每次输入都会导致每次输出量增加一倍,导致在几次输入后陷入长循环. 这是密码
const [direction,setDirection] = useState(Array(1).fill(0));
const directions = ["botNorth","botEast","botSouth","botWest"];
const [squares, setSquares] = useState(Array(5).fill().map(()=> Array(5).fill(null)));
useEffect(()=> {
const handleKeyDown = (e) =>{
e = e || window.event;
const nextSquares = squares.slice();
var nextDirection = direction.slice();
console.log(e.which);
if (e.keyCode == '38') {
// up arrow
}
else if (e.keyCode == '37') {
// left arrow
nextDirection[0]--;
if (nextDirection[0] < 0) {
nextDirection[0] = 3;
}
}
else if (e.keyCode == '39') {
// right arrow
}
setDirection(nextDirection);
nextSquares[location[0]][location[1]] = <img className={directions[nextDirection[0]]} src={bot}/>;
setSquares(nextSquares);
return () => document.removeEventListener('keydown', handleKeyDown);
};
document.addEventListener('keydown', handleKeyDown, true);
});
this is the resulting error each key was only pressed once
我try 在功能内部和外部移动添加和删除收听者,但这似乎没有什么区别
当我注释掉setSquare()
和setDirection()
时,它每个输入输出两次,而不是每次加倍