簡體   English   中英

在React中的秒表上設置localstorage.getItem()值

[英]Set the localstorage.getItem() value on the stopwatch in React

我創建了一個秒表,它將在后台運行。

當我運行時鍾時,將其設置為localstorage:

localStorage.setItem ('timerOn', true);

localStorage.setItem ('timerTime', Date.now () - this.state.timerTime) 

當我停止本地存儲中設置的時鍾時:

localStorage.setItem ('timerOn', false);

localStorage.setItem ('timerTime', Date.now () + this.state.timerTime);

我在時鍾上重置這些值時遇到問題:

LocalStorage.getItem ('timerOn')

LocalStorage.getItem ('timerTime')

有人可以建議嗎? 如果我關閉瀏覽器,該秒表將如何工作?

此處的示例: https : //stackblitz.com/edit/react-jj7jef

class Stopwatch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timerOn: false,
      timerStart: 0,
      timerTime: 0
    };
  }


  startTimer = () => {
    const { timerOn, timerTime, timerStart } = this.state;


    this.setState({
      timerOn: true,
      timerTime: this.state.timerTime,
      timerStart: Date.now() - this.state.timerTime
    });
    this.timer = setInterval(() => {
      this.setState({
        timerTime: Date.now() - this.state.timerStart
      });
    }, 10);

    localStorage.setItem('timerOn', true);
    localStorage.setItem('timerTime', Date.now() -       this.state.timerTime)
};

stopTimer = () => {
  this.setState({ timerOn: false });
  localStorage.setItem('timerOn', false);
  localStorage.setItem('timerTime', Date.now() +    
   this.state.timerTime);
  clearInterval(this.timer);
};

  render() {
    const { timerTime } = this.state;
    let centiseconds = ("0" + (Math.floor(timerTime / 10) % 100)).slice(-2);
    let seconds = ("0" + (Math.floor(timerTime / 1000) % 60)).slice(-2);
    let minutes = ("0" + (Math.floor(timerTime / 60000) % 60)).slice(-2);
    let hours = ("0" + Math.floor(timerTime / 3600000)).slice(-2);

    return (
      <div>
        <div className="Stopwatch-display">
          {hours} : {minutes} : {seconds} 
        </div>

        {(
          <button onClick={this.startTimer}>Start</button>
        )}

        {this.state.timerOn === true && this.state.timerTime > 0 && (
          <button onClick={this.stopTimer}>Stop</button>
        )}
      </div>
    );
  }
}

在localStorage setItem中,您必須這樣做

localStorage.setItem('Item name', JSON.stringify(item));

然后在get方法

let x = await localStorage.getItem('Item name'); let y = JSON.parse(x); console.log(y);

以下代碼將執行如下所述的功能:

  • 如果時鍾正在運行並關閉了窗口並在以后響應,它將仍在計數。
  • 如果我們停止時鍾並重新開始,它將從當前時間開始。
  • 如果我們停止時鍾並關閉窗口,請再次響應它會顯示最后的計數時間,您可以從此處開始。

如果需要,您還可以添加一個重置按鈕。

class Stopwatch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timerOn: false,
      timerStart: 0,
      timerTime: 0
    };
  }

  async componentDidMount() {
    let timerOn = localStorage.getItem('timerOn') === "true";
    let timerStart = localStorage.getItem('timerStart')
    let timerTime = localStorage.getItem('timerTime')

    await this.setState({
      timerOn: timerOn,
      timerStart: timerStart,
      timerTime: timerTime
    });

    if (timerOn) {
      this.startTimer()
    }
  }


  startTimer = (e) => {
    let { timerOn, timerTime = 0, timerStart = 0 } = this.state;

    if (e && timerOn) {
      return // stop continuous start button click
    }

    if (!timerOn) {
      // stop / pause state
      // start / resume from current time
      timerStart = Date.now() - timerTime
    }
    else if (timerOn) {
      // running state
      // calculate and compensate closed time
      timerTime = Date.now() - timerStart
    }

    this.setState({
      timerOn: true,
      timerTime: timerTime,
      timerStart: timerStart
    });

    this.timer = setInterval(() => {
      this.setState({
        timerTime: Date.now() - timerStart
      });
    }, 10);

    localStorage.setItem('timerOn', true);
    localStorage.setItem('timerStart', timerStart)
    localStorage.removeItem("timerTime")
  };

  stopTimer = () => {
    this.setState({ timerOn: false });
    localStorage.setItem('timerOn', false);
    localStorage.setItem('timerTime', this.state.timerTime);
    localStorage.removeItem("timerStart")
    clearInterval(this.timer);
  };

  render() {
    const { timerTime = 0 } = this.state;
    let centiseconds = ("0" + (Math.floor(timerTime / 10) % 100)).slice(-2);
    let seconds = ("0" + (Math.floor(timerTime / 1000) % 60)).slice(-2);
    let minutes = ("0" + (Math.floor(timerTime / 60000) % 60)).slice(-2);
    let hours = ("0" + Math.floor(timerTime / 3600000)).slice(-2);

    return (
      <div>
        <div className="Stopwatch-display">
          {hours} : {minutes} : {seconds}
        </div>

        {(
          <button onClick={this.startTimer}>Start</button>
        )}

        {this.state.timerOn === true && this.state.timerTime > 0 && (
          <button onClick={this.stopTimer}>Stop</button>
        )}
      </div>
    );
  }
}


render(<Stopwatch />, document.getElementById('root'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM