You need to enable JavaScript to run this app. React中如何使用useEffect结合setInterval实现时钟实时更新
优惠活动
大模型
产品
解决方案
定价
更多

React中如何使用useEffect结合setInterval实现时钟实时更新

问题定位

你在 setInterval 中直接传入 updateClock 作为回调,每秒仅执行该函数本身,没有把返回的时间值同步到 laDate 状态。React 状态未变化时不会触发重渲染,页面时间自然停留在第一次执行的结果上。
你不需要把动态变化的时间状态放入 useEffect 依赖数组:该定时器仅需在组件挂载时初始化一次、卸载时清理即可,原本的依赖数组传 [] 完全正确。

修复代码

把同步时间的逻辑抽成公共函数,同时给 setInterval 传入这个公共函数即可,修改后的 useEffect 如下:

useEffect(() => {
  // 抽离同步时间逻辑,避免重复写相同代码
  const syncTime = () => {
    const currTime = updateClock();
    setLaDate({ 
      yr: currTime[3], 
      mo: currTime[1], 
      dt: currTime[2], 
      hrs: currTime[4], 
      min: currTime[5], 
      sec: currTime[6], 
      day: currTime[0] 
    });
  };

  syncTime(); // 组件挂载时立即同步一次
  const interval = window.setInterval(syncTime, 1000); // 每秒触发同步

  return () => window.clearInterval(interval);
}, []);

这样修改后,定时器每秒触发时都会更新 React 状态,页面会自动渲染最新的时间。

内容的提问来源于stack exchange,提问作者crashwap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 17:24:01