react项目的初始化安装请参考:https://blog.csdn.net/u012335228/article/details/98884858
下面实验在浏览器将数据永久化
1.安装local storage js模块:
2.安装UI可视化模块,此处我们使用蚂蚁金服的开源项目antd react组件
3.安装(忽略警告信息,如果此处安装不上报error,可采用删除安装目录下的node_modules文件夹,重新执行npm install命令)
体验一下local storage
let store = require('store')
store.set('user','yzx')
console.log(store.get('user'))
store.remove('user')
console.log(store.get('user'))//undefined
console.log(store.get('user','default'))
store.set('user',{name:'tom',age:30})
console.log(store.get('user').name)
console.log('==================================')
store.set('city',{name:'shenzhen'})
store.each(function (value,key) {
console.log(key,value)
})
console.log('==================================')
store.clearAll();
store.each(function (value,key) {
console.log(key,value)
})
运行结果:
yzx
undefined
default
tom
==================================
user { name: 'tom', age: 30 }
city { name: 'shenzhen' }
==================================
4.项目完整代码:
react目录解构:
index.html内容(此处不在src目录,而在项目目录下):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React项目</title>
</head>
<body>
<h1>React项目 测试程序</h1>
<hr>
<div id="root"></div>
<script src="/assets/bundle.js"></script>
</body>
</html>
src目录中index.js
import React from 'react';
import ReactDom from 'react-dom'
import Create from './Create'
import TodoService from './service'
class Root extends React.Component {
constructor (props){
super(props)
this.service = new TodoService()
}
handlerCreate(event){
console.log('root handlercreate')
console.log('this=',this)
console.log('event=',event.target,event.target.value)
this.service.create(event.target.value)
}
render(){
return (
<div>
<Create onCreate={this.handlerCreate.bind(this)} />
</div>
)
}
}
ReactDom.render(<Root name='yzx' />,document.getElementById('root'))
src目录中service.js内容:
import store from 'store'
export default class TodoService{
static NAMESPACE = 'todo::'//prefix +str = key
todos = []
create(title){ //title 内容
console.log('service create')
const todo = {
key:TodoService.NAMESPACE + (new Date()).valueOf(),
title:title,
completed:false
}
this.todos.push(todo) //title key completed
store.set(todo.key,todo)
return todo
}
}
src目录中Create.js内容:
import React from 'react'
import 'antd/lib/input/style'
import 'antd/lib/card/style'
import {Input,Card} from 'antd'
export default props => (
<Card title="请输入待办事宜" extra={&l