ReactJS中的localStorage

时间:2017-07-24 09:51:14

标签: javascript reactjs local-storage

请帮助解决我的问题;

我有一个React组件。我在其中一个函数中有SetInterval。

我想:重新加载页面组件后应继续工作(setInterval正在运行且所有状态都在更新)

如何使用localStorage进行操作?

我试图保存所有状态,但是setInterval停止工作,这不是我需要的。

我的代码如下:



class StopWatch extends React.Component {
	constructor() {
		super();
		this.state = {
			startTime: null,
			endTime: null,
			isRunning: null,
			currentTime: 0,
			
		}
	}


	formatingTime = (time) => {
		const formattedTime = new Date(time);
		let hours = formattedTime.getUTCHours().toString();
		let minutes = formattedTime.getMinutes().toString();
		let seconds = formattedTime.getSeconds().toString();

		if (hours.length < 2) { hours = `0${hours}`; }

    	if (minutes.length < 2) { minutes = `0${minutes}`; }

    	if (seconds.length < 2) { seconds = `0${seconds}`; }

    	return (`${hours} : ${minutes} : ${seconds}`)


	}

	


	updateStopWatch = () => {
		let updatedTime = this.state.currentTime + 1000

		console.log(updatedTime)

		this.setState({
			currentTime: updatedTime
		})
	}



	startStopWatch = () => {

		let startTime = Date.now();



		this.setState({
			startTime: startTime,
			currentTime: 0,
			isRunning: true,
			runClock: setInterval(this.updateStopWatch, 1000)

		})
	}

	stopStopWatch = () => {
		let endTime = Date.now();

		this.setState({
			endTime: endTime,
			isRunning: false,
		})

		clearInterval(this.state.runClock)

	}




	render = () => {

		// console.log(this.state.isRunning)

		return (

			<div>
				<h1>{this.formatingTime(this.state.currentTime)}</h1>
			   <button onClick={this.startStopWatch}>Start</button>
			   <button onClick={this.stopStopWatch}>Stop</button>
			</div>

		)
	}
}



ReactDOM.render(<StopWatch />, document.getElementById('root'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id='root'></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

https://www.npmjs.com/package/react-interval这是我觉得适合你的事情