跳到主内容

React在useEffect使用setInterval时,setState无效

· 2分钟阅读

问题

在 useEffect 中使用 setInterval 实现定时器功能,每一秒 count 加 1,发现界面无法更新,具体查看下面代码

function Clock() {
const [time, setTime] = React.useState(0);
React.useEffect(() => {
const timer = setInterval(() => {
setTime(time + 1); // 每次都加1
}, 1000);
return () => {
window.clearInterval(timer);
};
}, []);

return (
<div>时钟: {time}</div>
);
}

ReactDOM.render(<Clock />, document.querySelector('#app'));

原因

不变主要是因为每次传递给 setInterval 的 timer 变量都是首次渲染的值。每次调用 setInterval 回调函数时,都无法获取到新的 timer。

解决

解决方法也很简单,只需要使用 setState 函数的形式即可。

function Clock() {
const [time, setTime] = React.useState(0);
React.useEffect(() => {
const timer = setInterval(() => {
setTime(prevTime => prevTime + 1);
}, 1000);
return () => {
window.clearInterval(timer);
};
}, []);

return (
<div>时钟: {time}</div>
);
}