简体   繁体   English

从组件安装反应计数时间

[英]React count time from component mount

In React / Javascript, how can one count time from when the component mounted? 在React / Javascript中,如何从组件安装开始算起时间? I wish to stay on a page a minimum time of 0,8 seconds. 我希望在页面上停留的最短时间为0.8秒。 So when component mounts, I wish to start a timer, that calculates whether the 0,8 seconds have passed. 因此,在安装组件时,我希望启动一个计时器,该计时器计算是否经过了0.8秒。 When I'm about to leave the page, I want to check whether that time has passed, and if not, then wait for the remain time, and then leave the page. 当我要离开页面时,我想检查该时间是否已经过去,如果没有,请等待剩余时间,然后离开页面。 How could I accomplish this? 我该怎么做?

React has multiple life-cycle events which one of them is componentDidMount . React有多个生命周期事件,其中之一是componentDidMount

componentDidMount() is invoked immediately after a component is mounted. 挂载组件后立即调用componentDidMount() Initialization that requires DOM nodes should go here. 需要DOM节点的初始化应在此处进行。 If you need to load data from a remote endpoint, this is a good place to instantiate the network request. 如果需要从远程端点加载数据,这是实例化网络请求的好地方。 Setting state in this method will trigger a re-rendering. 在此方法中设置状态将触发重新渲染。

Example

componentDidMount() {
  this.mountTime = (new Date).getTime();
}

onSomeActionThatTriggersUnmount() {
  const currentTime = (new Date).getTime();
  if(currentTime >= (this.mountTime + 800)) {
    // proceed with the unmount
  } else {
    // not enough time yet
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM