封装storage。js
var storage = {
set (key,value) {
localStorage.setItem(key, JSON.stringify(value))
},
get (key) {
return JSON.parse(localStorage.getItem(key))
},
remove (key) {
return localStorage.removeItem(key)
}
}
export default storage;
todolist
import React from 'react';
import storage from '../model/storage'
class TodoList2 extends React.Component {
constructor(props) {
super(props)
this.state = {
list: [
// {
// title: '录制ionic',
// checked: true
// },
// {
// title: '录制nodejs',
// checked: false
// }
// ,
// {
// title: '录制egg.js',
// checked: true
// },
// {
// title: '录制vue',
// checked: false
// }
],
name: 'TodoList2'
}
}
addData = (e) => {
// console.log(e)
if (e.keyCode === 13) {
let title = this.refs.title.value;
let tempList = this.state.list;
tempList.push({
title: title,
checked: false
})
this.setState({
list: tempList
})
//表单置为空
this.refs.title.value = '';
// localStorage.setItem('todoList', JSON.stringify(tempList))
storage.set('todoList',tempList)
}
}
delData = (key) => {
var temList = this.state.list
temList.splice(key, 1)
this.setState({
list: temList
})
storage.set('todoList',temList)
}
checkData = (key) => {
let tempList = this.state.list;
tempList[key].checked = !tempList[key].checked;
this.setState({
list: tempList
})
storage.set('todoList',tempList)
}
// 生命周期函数 页面加载就会触发
componentDidMount () {
var todoList = storage.get('todoList')
if (todoList) {
this.setState({
list: todoList
})
}
}
render () {
return (
<div>
{this.state.name}
<br />
<input ref='title' onKeyUp={this.addData} />
<h2>待办事项</h2>
<ul>
{
this.state.list.map((value, key) => {
if (!value.checked) {
return (
<li key={key}>
<input type='checkbox' checked={value.checked} onChange={this.checkData.bind(this, key)} />{value.title}-----------<button onClick={this.delData.bind(this, key)}>删除</button></li>
)
}
})
}
</ul>
<h2>已事项</h2>
<ul>
{
this.state.list.map((value, key) => {
if (value.checked) {
return (
<li key={key}>
<input type='checkbox' checked={value.checked} onChange={this.checkData.bind(this, key)} />{value.title}-----------<button onClick={this.delData.bind(this, key)}>删除</button></li>
)
}
})
}
</ul>
</div>
)
}
}
export default TodoList2;