我需要将类组件转换为功能组件,当我转换它的时候,它给了我一个无限循环。我怎样才能停止这个循环呢?
类组件ComponentDidMount代码
componentDidMount() {
setInterval(this.moveSnake, this.state.speed);
document.onkeydown = this.onKeyDown;
}
我为上面写的功能组件ComponentDidMount
useEffect(()=>{
document.onkeydown = onKeyDown
const interval = setInterval(() => {
moveSnake()
}, 200);
return () => clearInterval(interval);
},[]);
const moveSnake = ()=>{
let dots = [...snake];
let head = dots[dots.length-1];
switch(direction){
case "RIGHT":
head = [head[0]+2, head[1]];
break;
case "LEFT":
head = [head[0]-2, head[1]];
break;
case "UP":
head = [head[0], head[1]-2];
break;
case "DOWN":
head = [head[0], head[1]+2];
break;
}
dots.push(head);
dots.shift();
setSnake(dots);
console.log(dots);
}
在useEffect
:
document.onkeydown = onKeyDown;