【问题标题】:update seconds real time react [closed]更新秒实时反应[关闭]
【发布时间】:2021-09-04 16:54:58
【问题描述】:

我有这个代码:

var Difference = new Date().getTime() - new Date('November 15, 2020').getTime();
var seconds = Math.floor(Difference / 3600) % 60;

我想在我的网站中显示变量“秒”并实时更新秒而不刷新页面,我该怎么做?

【问题讨论】:

标签: javascript reactjs time


【解决方案1】:

在阅读答案之前,请阅读 side effectsstates in react 和 setTimeout

你可以结合useStateuseEffect,首先,你必须创建一个状态

// Assuming you are using functional components
const [time, setTime] = useState(
    // add whatever initial value suitable for you
);

然后你应该制作一个每秒更新状态的效果,你应该编写如下内容

useEffect(() => {
    // change the timer every one second
    const timer = setTimeout(() => {
      setTime(updateTime(time)); // use update the time according to your logic
    }, 1000);
    // a cleanup function 
    return () => {
      clearTimeout(timer);
    }; 
   // trigger the effect only when the timer change 
  }, [time]);

【讨论】:

    猜你喜欢
    • 2017-05-08
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2014-01-16
    相关资源
    最近更新 更多