【问题标题】:ReactJS Stopwatch, how to handle localstorage dataReactJS 秒表,如何处理本地存储数据
【发布时间】:2019-07-03 11:56:53
【问题描述】:

我有计算时间的组件(秒表)。一切正常。启动、停止时钟复位。我想添加功能,当我停止时钟 (handleTimerStop) 时将当前状态设置为 localstorage,以防我关闭浏览器并想要返回并想要从我离开时钟暂停的地方开始。因此,当我停止时钟项目设置为本地存储但当我想重新启动时钟时,它不会从本地存储中获取数据,而是从头开始。能否请你帮忙?如果有人能优化我的代码,那就太好了,因为我觉得它可以做得更好。

谢谢

    import React, { Component } from "react";

export default class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      timerStarted: false,
      timerStopped: true,
      hours: 0,
      minutes: 0,
      seconds: 0
    };
  }
  componentDidMount() {
    if (!localStorage.getItem("sec") === null) {
      this.setState({
        seconds: localStorage.getItem("sec")
      });
    }
    if (!localStorage.getItem("min") === null) {
      this.setState({
        seconds: localStorage.getItem("min")
      });
    }
    if (!localStorage.getItem("hour") === null) {
      this.setState({
        seconds: localStorage.getItem("hours")
      });
    }
  }

  handleTimerStart = e => {
    e.preventDefault();

    if (localStorage.getItem("sec") === null) {
      this.setState({
        seconds: 0
      });
    } else {
      this.setState({
        seconds: localStorage.getItem("sec")
      });
    }
    if (localStorage.getItem("min") === null) {
      this.setState({
        minutes: 0
      });
    } else {
      this.setState({
        minutes: localStorage.getItem("min")
      });
    }
    if (localStorage.getItem("hour") === null) {
      this.setState({
        hours: 0
      });
    } else {
      this.setState({
        hours: localStorage.getItem("hour")
      });
    }

    if (this.state.timerStopped) {
      this.timer = setInterval(() => {
        this.setState({ timerStarted: true, timerStopped: false });
        if (this.state.timerStarted) {
          if (this.state.seconds >= 60) {
            this.setState(prevState => ({
              minutes: prevState.minutes + 1,
              seconds: localStorage.getItem("sec")
            }));
          }
          if (this.state.minutes >= 60) {
            this.setState(prevState => ({
              hours: prevState.hours + 1,
              minutes: localStorage.getItem("min"),
              seconds: localStorage.getItem("sec")
            }));
          }
          this.setState(prevState => ({ seconds: prevState.seconds + 1 }));
        }
      }, 1000);
    }
  };

  handleTimerStop = () => {
    this.setState({ timerStarted: false, timerStopped: true });
    clearInterval(this.timer);
    localStorage.setItem("sec", this.state.seconds);
    localStorage.setItem("min", this.state.minutes);
    localStorage.setItem("hour", this.state.hours);
  };

  handelResetTimer = () => {
    this.setState({
      timerStarted: false,
      timerStopped: true,
      hours: 0,
      minutes: 0,
      seconds: 0
    });
  };
  render() {
    return (
      <div className="container">
        <h2 className="text-center"> React Based Timer </h2>
        <div className="timer-container">
          <div className="current-timer">
            {this.state.hours +
              ":" +
              this.state.minutes +
              ":" +
              this.state.seconds}
          </div>
          <div className="timer-controls">
            <button className="btn btn-success" onClick={this.handleTimerStart}>
              Start Timer
            </button>
            <button className="btn btn-alert" onClick={this.handleTimerStop}>
              Stop Timer
            </button>
            <button className="btn btn-info"> Capture Time </button>
            <button className="btn btn-danger" onClick={this.handelResetTimer}>
              {" "}
              Reset!{" "}
            </button>
          </div>
        </div>
      </div>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这些比较是您的问题。

    !null === null or !'23' === null ... false always.
    
    
    
    if (!localStorage.getItem("sec") === null) {
      this.setState({
        seconds: localStorage.getItem("sec")
      });
    }
    if (!localStorage.getItem("min") === null) {
      this.setState({
        seconds: localStorage.getItem("min")
      });
    }
    if (!localStorage.getItem("hour") === null) {
      this.setState({
        seconds: localStorage.getItem("hours")
      });
    }
    

    【讨论】:

    • 你能解决它吗?
    【解决方案2】:

    这不是您具体问题的答案,而是 imo。更好的代码方法

    这个实现是

    • 独立于渲染间隔,
    • 仅在您启动/停止/重置时写入 localStorage
    • 并且没有失去同步(即使它根本没有被渲染)

    .

    import React, { Component } from "react";
    
    export default class Timer extends Component {
      constructor(props) {
        super(props);
    
        try {
          this.state = JSON.parse(localStorage.getItem(this.props.localStorage));
        } catch (error) {}
    
        if (!this.state) {
          this.state = this.saveChanges({
            running: false,
            value: 0
          });
        }
      }
    
      componentWillMount() {
        if (this.state.running) {
          this.timer = setInterval(
            () => this.forceUpdate(),
            this.props.interval | 0
          );
        }
      }
    
      componentWillUnmount() {
        if (this.state.running) {
          clearInterval(this.timer);
        }
      }
    
      saveChanges(state) {
        console.log("saveChanges", this.props.localStorage, state);
        if (this.props.localStorage) {
          localStorage.setItem(this.props.localStorage, JSON.stringify(state));
        }
        return state;
      }
    
      start = () => {
        const now = Date.now();
    
        this.setState(({ running, value }) => {
          if (running) return null;
    
          this.timer = setInterval(
            () => this.forceUpdate(),
            this.props.interval | 0
          );
    
          return this.saveChanges({
            running: true,
            value: value - now
          });
        });
      };
    
      stop = () => {
        const now = Date.now();
    
        this.setState(({ running, value }) => {
          if (!running) return null;
    
          clearInterval(this.timer);
          return this.saveChanges({
            running: false,
            value: value + now
          });
        });
      };
    
      reset = () => {
        const now = Date.now();
    
        this.setState(({ running, value }) => {
          return this.saveChanges({
            running: false,
            value: 0
          });
    
          //just reset the timer to 0, don' stop it
          //return this.saveChanges({
          //  running,
          //  value: running? -now: 0
          //});
        });
      };
    
      render() {
        const {
          start, stop, reset,
          state: { running, value }
        } = this;
    
        const timestamp = running ? Date.now() + value : value;
        const h = Math.floor(timestamp / 3600000);
        const m = Math.floor(timestamp / 60000) % 60;
        const s = Math.floor(timestamp / 1000) % 60;
        const ms = timestamp % 1000;
    
        const _ = (nr, length = 2, padding = 0) =>
          String(nr).padStart(length, padding);
    
        return (
          <div className="container">
            <h2 className="text-center"> React Based Timer </h2>
            <div className="timer-container">
              <div className="current-timer">
                {_(h) + ":" + _(m) + ":" + _(s) + "." + _(ms, 3)}
              </div>
              <div className="timer-controls">
                <button className="btn btn-success" onClick={start}>
                  Start Timer
                </button>
    
                <button className="btn btn-alert" onClick={stop}>
                  Stop Timer
                </button>
    
                <button className="btn btn-danger" onClick={reset}>
                  Reset!
                </button>
              </div>
            </div>
          </div>
        );
      }
    }
    

    检查此沙盒

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 2012-12-10
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多