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

Zai*_*shi 6 javascript time-tracking reactjs 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,
    });
}
Run Code Online (Sandbox Code Playgroud)

这是 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}`,
);
Run Code Online (Sandbox Code Playgroud)

}

mas*_*enz 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.
     */
);
Run Code Online (Sandbox Code Playgroud)