首页 > 解决方案 > 单击另一个页面上的按钮后如何启动计时器?

问题描述

我有几个问题想放在一起。

  1. 单击另一个页面上的按钮后,如何启动倒数计时器?
  2. 单击计时器后,如何防止在页面刷新时重置?(我找到了使用 cookie 等的示例,但我找不到将它们添加到下面代码中的方法)。
  3. 计时器只会在按下按钮时停止。
import React, { Component } from 'react'

class Timer extends Component {
    
    state = {
        minutes: 1,
        seconds: 0,
    }

    componentDidMount() {
        this.myInterval = setInterval(() => {
            const { seconds, minutes } = this.state

            if (seconds > 0) {
                this.setState(({ seconds }) => ({
                    seconds: seconds - 1
                }))
            }
            if (seconds === 0) {
                if (minutes === 0) {
                    clearInterval(this.myInterval)
                } else {
                    this.setState(({ minutes }) => ({
                        minutes: minutes - 1,
                        seconds: 59
                    }))
                }
            } 
        }, 1000)
    }

    componentWillUnmount() {
        clearInterval(this.myInterval)
    }

    render() {
        const { minutes, seconds } = this.state
        return (
            <div>
                { minutes === 0 && seconds === 0
                    ? <h1></h1>
                    : <h1>Timer is counting: {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
                }
            </div>
        )
    }
}

export default Timer 

任何帮助将不胜感激。先感谢您 :)

标签: javascriptreactjsreact-nativecomponents

解决方案


  1. 定义倒计时时间

const TIMER_TIME = 120; // time of the timer in seconds

  1. 通过保存定时器启动时间来启动超时

localStorage.setItem('timer-start', new Date().getTime()); // can be called from any page, trigger by any thing

  1. 处理组件中的剩余时间
class Timer extends React.Component {
    
    constructor(props) {
        super(props);
        this.state = this.calculateTimer();
    }
    calculateTimer = () => {
      const startTime = localStorage.getItem('timer-start'); // get data of time start
      if(!startTime) return {seconds:0,minutes:0};
      const timeLeft = TIMER_TIME - (new Date().getTime() - startTime) / 1000; // timeleft = timer time -time over
      if(timeLeft <= 0) { // reset timer if its finish
        localStorage.removeItem('timer-start');
        clearTimeout(this.myInterval);
        return {seconds:0,minutes:0}
      }
      return {minutes: Math.floor(timeLeft/60), seconds: Math.floor(timeLeft%60)}
    }
    componentDidMount() {
        this.myInterval = setInterval(() => this.setState(this.calculateTimer()), 1000)
    }

    componentWillUnmount() {
        clearInterval(this.myInterval)
    }

    render() {
        const { minutes, seconds } = this.state
        return (
            <div>
                { minutes === 0 && seconds === 0
                    ? <h1></h1>
                    : <h1>Timer is counting: {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
                }
            </div>
        )
    }
}

推荐阅读