[web 前端] web本地存儲(localStorage、sessionStorage)


cp from : https://blog.csdn.net/mjzhang1993/article/details/70820868

web 本地存儲 (localStorage、sessionStorage)

說明

對瀏覽器來說,使用 Web Storage 存儲鍵值對比存儲 Cookie 方式更直觀,而且容量更大,它包含兩種:localStorage 和 sessionStorage

  1. sessionStorage(臨時存儲) :為每一個數據源維持一個存儲區域,在瀏覽器打開期間存在,包括頁面重新加載

  2. 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

Application

結合 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();
       }
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM