这里我定义了seconds和timeArr
const [spaceEventCounter, setSpaceEventCounter] = useState(0);
const [isRunning, setIsRunning] = useState(false); // isRunning = true -> secondsCounter = running
const [timeArr, setTimeArr] = useState([8.55, 9.55, 10.55, 11.55, 12.55]);
const [seconds, setSeconds] = useState(0);
如果isRunning = true/false,则此useEffect启动并停止计数器
useEffect(() => {
let interval;
if (isRunning) {
interval = setInterval(() => {
setSeconds(seconds => Number((seconds + 0.01).toFixed(2)));
}, 10);
} else {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isRunning]);
在第三个if语句的handleKeyUp函数中运行setTimeArr时,会出现此问题
useEffect(() => {
const handleKeyDown = (event) => {
if (event.code !== "Space") return;
if (spaceEventCounter === 0) {
setSpaceEventCounter(1);
}
if (spaceEventCounter === 2) {
setIsRunning(false);
setTimeArr([...timeArr, seconds]);
setSpaceEventCounter(3);
}
};
const handleKeyUp = (event) => {
if (event.code !== "Space") return;
if (spaceEventCounter === 1) {
setIsRunning(true)
setSpaceEventCounter(2);
} else if (spaceEventCounter === 3) {
setSpaceEventCounter(0);
}
} ;
document.addEventListener("keydown", handleKeyDown);
document.addEventListener("keyup", handleKeyUp);
return () => {
document.removeEventListener("keydown", handleKeyDown);
document.removeEventListener("keyup", handleKeyUp);
};
}, [spaceEventCounter]);
我不知道该尝试什么
1条答案
按热度按时间ljsrvy3e1#
我看到的是在
useEffect
中声明函数。此
useEffect
挂接具有spaceEventCounter
作为依赖项。换句话说,每次
spaceEventCounter
发生变化时,您都要重新声明函数并添加事件侦听器,而实际上您需要在安装组件后添加事件侦听器。我会尝试使用最后一个
useEffect
,其中包含一个空的依赖项数组。