function func(){
const [time, setTime] = useState(10);
var timeRemaining = 10;
const myInterval = setInterval(() => {
if (timeRemaining > 0) {
timeRemaining = timeRemaining - 1;
setTime(timeRemaining);
} else { clearInterval(myInterval) }
}, 1000);
return <div>{time}</div>
}
如果我这样写的话,它要感谢普通变量“ timeRemaining”,但是,如果我写了:
const myInterval = setInterval(() => {
if (time> 0) {
setTime(time-1);
} else { clearInterval(myInterval) }
}, 1000);
它将停止更新{time}
使用效果来控制间隔,使用ref保持对间隔计时器参考的引用,并使用功能状态更新以正确管理状态。
功能组件代码:
function App() {
const timerRef = useRef(null);
const [time, setTime] = useState(10);
useEffect(() => {
timerRef.current = setInterval(() => setTime(t => t - 1), 1000);
return () => clearInterval(timerRef.current);
}, []);
useEffect(() => {
if (time === 0) {
clearInterval(timerRef.current);
timerRef.current = null;
}
}, [time]);
return <div>{time}</div>;
}
使用setTime的功能版本,尽管我建议您也将间隔放入useEffect中进行清理
setTime((time) => {
if (time > 0) {
return time - 1;
}
clearInterval(myInterval);
return time;
});
具有useEffect:
function func() {
const [time, setTime] = useState(10);
var timeRemaining = 10;
useEffect(() => {
const myInterval = setInterval(() => {
setTime((time) => {
if (time > 0) {
return time - 1;
}
clearInterval(myInterval);
return time;
});
}, 1000);
return () => {
clearInterval(myInterval);
};
}, [input]);
return <div>{timeRemaining}</div>;
}