数据持久化就是缓存数据
import React, { Component } from 'react';
class Todolist extends Component {
constructor() {
super();
this.state = {
undoList:[],
completedList: [],
temptrue:true,
tempfalse:false
}
var undolistSession = localStorage.getItem('undolist');
var completedSession = localStorage.getItem('Completedlist');
//注意:这里直接赋值,不是用setState的方法
if (undolistSession != null) {
this.state.undoList = JSON.parse(undolistSession);
}
if (completedSession != null) {
this.state.completedList = JSON.parse(completedSession);
}
}
add = () =>{
var tempList = this.state.undoList;
tempList.push(this.refs.newContent.value)
this.setState({
undoList : tempList
})
//缓存数据
localStorage.setItem('undolist',JSON.stringify(tempList));
}
delete(key){
var tempList = this.state.undoList;
this.state.undoList.splice(key, 1);
this.setState({
undoList : tempList
})
//缓存数据
localStorage.setItem('undolist',JSON.stringify(tempList));
}
deleteCompleted(key){
var tempList = this.state.completedList;
this.state.completedList.splice(key, 1);
this.setState({
completedList : tempList
})
//缓存数据
localStorage.setItem('Completedlist',JSON.stringify(tempList));
}
changeToCompleted(key) {
var tempList = this.state.undoList;
var item = tempList[key];
this.state.undoList.splice(key, 1);
this.setState({
undoList : tempList
})
var newTempList = this.state.completedList;
newTempList.push(item);
this.setState({
completedList : newTempList
})
//缓存数据
localStorage.setItem('undolist',JSON.stringify(tempList));
localStorage.setItem('Completedlist',JSON.stringify(newTempList));
}
changeToUndo(key) {
var tempList = this.state.completedList;
var item = tempList[key];
this.state.completedList.splice(key, 1);
this.setState({
completedList : tempList
})
var newTempList = this.state.undoList;
newTempList.push(item);
this.setState({
undoList : newTempList
})
//缓存数据
localStorage.setItem('undolist',JSON.stringify(newTempList));
localStorage.setItem('Completedlist',JSON.stringify(tempList));
}
render() {
return (
<div>
<input ref='newContent'></input>
<button onClick={this.add}>增加</button>
<hr/>
<h1>待办事项</h1>
<ul>
{
this.state.undoList.map((value,key) => {
return (
<li key={key}>
<input type='checkbox' checked={this.state.tempfalse} onChange={this.changeToCompleted.bind(this,key)}/>
{value}
<button onClick={this.delete.bind(this,key)}>删除</button>
</li>
)
})
}
</ul>
<h1>已完成事项</h1>
<ul>
{
this.state.completedList.map((value,key) => {
return (
<li key={key}>
<input type='checkbox' checked={this.state.temptrue} onChange={this.changeToUndo.bind(this,key)}/>
{value}
<button onClick={this.deleteCompleted.bind(this,key)}>删除</button>
</li>
)
})
}
</ul>
</div>
);
}
}
export default Todolist;