如何计算特定屏幕用户在React Native上花费的时间

问题描述

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

这是我的代码

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}`,);

}

解决方法

我不是React开发人员,但这相当简单,这就是方法。

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.
     */
);
,

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

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>
  );
};

查看结果: chronometer

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...