對瀏覽器來講,使用 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(); } }