我想对usestate或其他钩子做出反应.倒计时60秒.如何



这是我实现计数器的尝试。

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} />

相关内容

  • 没有找到相关文章

最新更新