web本地儲存(localStorage、sessionStorage)
阿新 • • 發佈:2019-01-03
web 本地儲存 (localStorage、sessionStorage)
說明
對瀏覽器來說,使用 Web Storage 儲存鍵值對比儲存 Cookie 方式更直觀,而且容量更大,它包含兩種:localStorage 和 sessionStorage
sessionStorage(臨時儲存) :為每一個數據源維持一個儲存區域,在瀏覽器開啟期間存在,包括頁面重新載入
localStorage(長期儲存) :與 sessionStorage 一樣,但是瀏覽器關閉後,資料依然會一直存在
API
sessionStorage 和 localStorage 的用法基本一致,引用型別的值要轉換成JSON
1. 儲存資料到本地
const info = {
name: 'Lee',
age: 20,
id: '001'
};
sessionStorage.setItem('key', JSON.stringify(info));
localStorage.setItem('key', JSON.stringify(info));
2. 從本地儲存獲取資料
var data1 = JSON.parse(sessionStorage.getItem('key'));
var data2 = JSON .parse(localStorage.getItem('key'));
3. 本地儲存中刪除某個儲存的資料
sessionStorage.removeItem('key');
localStorage.removeItem('key');
4. 刪除所有儲存的資料
sessionStorage.clear();
localStorage.clear();
5. 監聽本地儲存的變化
Storage 發生變化(增加、更新、刪除)時的 觸發,同一個頁面發生的改變不會觸發,只會監聽同一域名下其他頁面改變 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);
})
瀏覽器檢視方法
- 進入開發者工具
- 選擇 Application
- 在左側 Storage 下 檢視 Local Storage 和 Session Storage
結合 React 實現使用者基本資料的本地儲存
介面UI方面的就不展示了,編寫兩個元件:
<Login/>
負責登入輸入驗證;<Home/>
專案主頁,展示使用者資訊
1. 需求
<Login/>
元件可以得到使用者輸入的賬號、密碼,向伺服器傳送請求後獲得{id:'',name:'',tel:''}
- 這些資料是
<Home/>
元件正確展示所必須的,否則就會跳轉到登入頁 - 我們需要讓使用者 直接開啟主頁就可以展示使用者資訊,不要再跳轉到登入頁
2. 實現
- 使用者在登入頁填寫登入資訊後,將登入資料儲存到
localStorage
中 - 進入主頁,首先獲取
localStorage
中的資料,存在資料在直接展示,否則進入登入頁
1. 登入資料儲存到 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()
}));
}
2. 進入主頁獲取 localStorage
中資料
在主頁路由中配置進入頁面時處理函式
<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();
}
}