4

我正在尝试计算用户打开特定屏幕时的时间,当他进入屏幕时时间开始,当我退出屏幕时时间停止并给出在屏幕上花费的时间

这是我的代码:

componentDidMount = () => {
    
    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    this.setState({
      startHour: hours,
      startMin: minutes,
      startSeconds: seconds,
    });
}

这是 ComponentWillunmount

componentWillUnmount() {

let date = new Date();
let endHours = date.getHours();
let endMinutes = date.getMinutes();
let endSeconds = date.getSeconds();
console.log(`${endHours}:${endMinutes}:${endSeconds}`);
console.log(
  `${this.state.startHour}:${this.state.startMin}:${this.state.startSeconds}`,
);

}

4

2 回答 2

1

看这段代码,这是一个功能组件。

import React, { useState, useEffect } from 'react';

export const Chronometer = () => {
  const [time, setTime] = useState({
    seconds: 0,
    minutes: 0,
    hours: 0,
  });

  useEffect(() => {
    let isCancelled = false;

    const advanceTime = () => {
      setTimeout(() => {
        let nSeconds = time.seconds;
        let nMinutes = time.minutes;
        let nHours = time.hours;

        nSeconds++;

        if (nSeconds > 59) {
          nMinutes++;
          nSeconds = 0;
        }
        if (nMinutes > 59) {
          nHours++;
          nMinutes = 0;
        }
        if (nHours > 24) {
          nHours = 0;
        }

        !isCancelled && setTime({ seconds: nSeconds, minutes: nMinutes, hours: nHours });
      }, 1000);
    };
    advanceTime();

    return () => {
      //final time:
      console.log(time);
      isCancelled = true;
    };
  }, [time]);

  return (
    <div>
      <p>
        {`
          ${time.hours < 10 ? '0' + time.hours : time.hours} :
          ${time.minutes < 10 ? '0' + time.minutes : time.minutes} :
          ${time.seconds < 10 ? '0' + time.seconds : time.seconds}
        `}
      </p>
    </div>
  );
};

看结果: 计时器

要显示 useEffect 钩子中的总时间,您可以返回一个函数,在此示例中,我使用 console.log,但如果您想将其传递给其他组件,您可以提升状态或在 URL 参数中传递它

于 2020-08-26T06:45:29.247 回答
0

我不是反应开发者,但这相当简单,这就是方法。

componentDidMount = () => {
   /* On init set the start time
      Also: multiplying new Date() by 1 will return a timestamp
    */
   this.startTime = new Date() * 1;
}

componentWillUnmount() {
    /* Then on view destroy set the endTime */
    let endTime = new Date() * 1;
    /* Subtract the end time with start time, since endTime has greater value. The result
     is the difference between start and end time in milliseconds.
     */
    let elapsed = endTime - this.startTime;
    /* The result is in milliseconds so:
       elapsed / 1000 -> is seconds
       elapsed / 1000 / 60 -> is minutes
       etc.
     */
);
于 2020-08-26T06:21:08.293 回答