对每个条目进行 useEffect handleKeyDown 复制输出

问题描述 投票:0回答:1

每次输入都会导致输出量加倍,导致在几次输入后陷入长循环。 这是代码

  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);
});

这是每个键只按一次而产生的错误 screenshot of error

我尝试在函数内部和外部移动添加和删除侦听器,但似乎没有什么区别 当我注释掉

setSquare()
setDirection()
时,它每个输入输出两次,而不是每次加倍

javascript reactjs
1个回答
0
投票

需要知道的一件事是,由于您在添加事件侦听器时设置选项,因此在删除事件侦听器时也需要相同的选项。所以

document.addEventListener('keydown', handleKeyDown, true);
需要
document.removeEventListener('keydown', handleKeyDown, true);

我还会使用这些参数将依赖项数组添加到您的

useEffect
setDirection, setSquares, squares, direction

© www.soinside.com 2019 - 2024. All rights reserved.