【发布时间】: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