API
sessionStorage 和 localStorage 的用法基本一致,引用類型的值要轉(zhuǎn)換成JSON
- 保存數(shù)據(jù)到本地
const info = {
name: 'Lee',
age: 20,
id: '001'
};
sessionStorage.setItem('key', JSON.stringify(info));
localStorage.setItem('key', JSON.stringify(info));
- 從本地存儲(chǔ)獲取數(shù)據(jù)
var data1 = JSON.parse(sessionStorage.getItem('key'));
var data2 = JSON.parse(localStorage.getItem('key'));
- 本地存儲(chǔ)中刪除某個(gè)保存的數(shù)據(jù)
sessionStorage.removeItem('key');
localStorage.removeItem('key');
- 刪除所有保存的數(shù)據(jù)
sessionStorage.clear();
localStorage.clear();
- 監(jiān)聽(tīng)本地存儲(chǔ)的變化
Storage 發(fā)生變化(增加吃媒、更新、刪除)時(shí)的 觸發(fā),同一個(gè)頁(yè)面發(fā)生的改變不會(huì)觸發(fā)睹晒,只會(huì)監(jiān)聽(tīng)同一域名下其他頁(yè)面改變 Storage
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);
})
- 登錄數(shù)據(jù)存儲(chǔ)到 localStorage 中
在登錄頁(yè)路由中配置離開(kāi)頁(yè)面時(shí)處理函數(shù),存儲(chǔ)的數(shù)據(jù)一小時(shí)內(nèi)有效
<Route path="login" component={Login} onLeave={leaveLoginPage}/>
import store from '../store/index';
// login 頁(yè)面 離開(kāi)時(shí)邏輯
export const leaveLoginPage = () => {
// 離開(kāi) login 頁(yè)面 更新 localStorage 中的數(shù)據(jù)
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()
}));
}
- 進(jìn)入主頁(yè)獲取 localStorage 中數(shù)據(jù)
在主頁(yè)路由中配置進(jìn)入頁(yè)面時(shí)處理函數(shù)
<Route path="home" component={Home} onEnter={enterHomePage}>
import store from '../store/index';
// show 頁(yè)面進(jìn)入 邏輯
export const enterHomePage = (nextState, replace, next) => {
const rootState = store.getState().rootReducer;
const userInfoState = JSON.parse(localStorage.getItem('userInfoState'));
// 判斷store 中是否有用戶登錄數(shù)據(jù)
if (!rootState.isLogin) {
// 不含有用戶登錄數(shù)據(jù)括细,判斷 localStorage 中的數(shù)據(jù)是否可以使用
const pass = userInfoState && userInfoState.timestamp && new Date().getTime() - userInfoState.timestamp <= 60 * 60 * 1000;
if (pass) {
// userInfoState 存在伪很,并且上一次離開(kāi)在一小時(shí)以內(nèi),可以讀取 localStorage 數(shù)據(jù)
const storedUserInfo = userInfoState.userInfo;
// 'LOGIN' 將獲取的數(shù)據(jù)更新到 store 中
store.dispatch({type: 'LOGIN', msg: storedUserInfo});
next();
} else {
// userInfoState 不存在 或者 已過(guò)期奋单,則跳轉(zhuǎn)到登錄頁(yè)
replace('/login');
next();
}
} else {
// store 中 含有 用戶登錄數(shù)據(jù)锉试,直接進(jìn)入相應(yīng)頁(yè)面
next();
}
}