【发布时间】:2021-09-26 06:05:35
【问题描述】:
我在这里完成了一些问答,但无法理解我做错了什么。以下组件在控制台中打印0s,并没有按预期更新 DOM。
const NotifPopup = ({ notif, index, closeHandler }) => {
const [timer, setTimer] = useState(0);
useEffect(() => {
const timerRef = setInterval(() => {
if (timer === 3) {
clearInterval(timerRef);
closeHandler(index);
} else {
console.log("timer", timer);
setTimer(timer + 1);
}
}, 1000);
}, []); // only run on mount
return (<div className="notifPopup">
<span className=""></span>
<p>{notif.message}</p>
<span className="absolute bottom-2 right-8 text-xs text-oldLace">{`closing in ${timer}s`}</span>
</div>);
};
为什么setInterval 在控制台打印0s 流而不更新DOM?
【问题讨论】:
标签: javascript reactjs asynchronous setinterval