我有一个带有受控输入的组件.此组件也是Timer组件的父级.Timer组件使用setTimeout从20倒计时到0.现在,子组件在父组件中的每个击键(因此状态更改)时重新呈现.
const Timer = () => {
const [secondsLeft, setSecondsLeft] = useState(20);
if (secondsLeft) {
setTimeout(() => setSecondsLeft(secondsLeft - 1), 1000);
}
const displayTime = '00:' + String(secondsLeft).padStart(2, '0');
if (secondsLeft > 0) {
return <span>Time left {displayTime}</span>;
}
return <span>You're out of time!</span>;
};
我的问题是,为什么倒计时计时器工作正常,无论我在父输入元素中输入多快,它的间隔总是精确到1秒.为什么重新呈现不会影响setTimeout?