对浏览器来讲,使用 Web Storage 存储键值对比存储 Cookie 方式更直观,并且容量更大,它包含两种:localStorage 和 sessionStoragejavascript
sessionStorage(临时存储) :为每个数据源维持一个存储区域,在浏览器打开期间存在,包括页面从新加载java
localStorage(长期存储) :与 sessionStorage 同样,可是浏览器关闭后,数据依然会一直存在react
sessionStorage 和 localStorage 的用法基本一致,引用类型的值要转换成JSONweb
const info = { name: 'Lee', age: 20, id: '001' }; sessionStorage.setItem('key', JSON.stringify(info)); localStorage.setItem('key', JSON.stringify(info));
var data1 = JSON.parse(sessionStorage.getItem('key')); var data2 = JSON.parse(localStorage.getItem('key'));
sessionStorage.removeItem('key'); localStorage.removeItem('key');
sessionStorage.clear(); localStorage.clear();
Storage 发生变化(增长、更新、删除)时的 触发,同一个页面发生的改变不会触发,只会监听同一域名下其余页面改变 Storageapi
window.addEventListener('storage', function (e) { console.log('key', e.key); console.log('oldValue', e.oldValue); console.log('newValue', e.newValue); console.log('url', e.url); })
界面UI方面的就不展现了,编写两个组件:
<Login/>
负责登陆输入验证;<Home/>
项目主页,展现用户信息浏览器
<Login/>
组件能够获得用户输入的帐号、密码,向服务器发送请求后得到 {id:'',name:'',tel:''}
<Home/>
组件正确展现所必须的,不然就会跳转到登陆页localStorage
中localStorage
中的数据,存在数据在直接展现,不然进入登陆页localStorage
中在登陆页路由中配置离开页面时处理函数,存储的数据一小时内有效服务器
<Route path="login" component={Login} onLeave={leaveLoginPage}/>
import store from '../store/index'; // login 页面 离开时逻辑 export const leaveLoginPage = () => { // 离开 login 页面 更新 localStorage 中的数据 const {id, name, tel} = store.getState().rootReducer; const userInfo = {id, name, tel}; const userInfoState = localStorage.getItem('userInfoState'); if (userInfoState) { // 若是本地存在 userInfoState 将其移除 localStorage.removeItem('userInfoState'); } localStorage.setItem('userInfoState', JSON.stringify({ userInfo, timestamp: new Date().getTime() })); }
localStorage
中数据在主页路由中配置进入页面时处理函数session
<Route path="home" component={Home} onEnter={enterHomePage}>
import store from '../store/index'; // show 页面进入 逻辑 export const enterHomePage = (nextState, replace, next) => { const rootState = store.getState().rootReducer; const userInfoState = JSON.parse(localStorage.getItem('userInfoState')); // 判断store 中是否有用户登陆数据 if (!rootState.isLogin) { // 不含有用户登陆数据,判断 localStorage 中的数据是否可使用 const pass = userInfoState && userInfoState.timestamp && new Date().getTime() - userInfoState.timestamp <= 60 * 60 * 1000; if (pass) { // userInfoState 存在,而且上一次离开在一小时之内,能够读取 localStorage 数据 const storedUserInfo = userInfoState.userInfo; // 'LOGIN' 将获取的数据更新到 store 中 store.dispatch({type: 'LOGIN', msg: storedUserInfo}); next(); } else { // userInfoState 不存在 或者 已过时,则跳转到登陆页 replace('/login'); next(); } } else { // store 中 含有 用户登陆数据,直接进入相应页面 next(); } }