这是我实现计数器的尝试。
const [stateTime, setTime] = useState(time);
let countDown = () => {
setTime(stateTime - 1);
};
let intervalTimer = setInterval(countDown, 1000);
setTimeout(() => {
clearInterval(intervalTimer);
}, 5000);
但它不起作用,我不知道为什么。
以下是
const CountDown = ({ seconds }) => {
const [timeLeft, setTimeLeft] = useState(seconds);
useEffect(() => {
// exit early when we reach 0
if (!timeLeft) return;
// save intervalId to clear the interval when the
// component re-renders
const intervalId = setInterval(() => {
setTimeLeft(timeLeft - 1);
}, 1000);
// clear interval on re-render to avoid memory leaks
return () => clearInterval(intervalId);
// add timeLeft as a dependency to re-rerun the effect
// when we update it
}, [timeLeft]);
return (
<div>
<h1>{timeLeft}</h1>
</div>
);
};
在您的父组件中
<CountDown seconds={60} />