Web Local Storage (localstorage, sessionstorage)

Source: Internet
Author: User
Tags sessionstorage

Web Local Storage (localstorage, sessionstorage) description

For browsers, using Web Storage to store key values compared to storing cookies is more intuitive and more capacity, it contains two kinds: Localstorage and Sessionstorage

  1. Sessionstorage (Temporary storage): maintains a storage area for each data source that exists during browser opening, including page reload

  2. Localstorage (long-term storage): Same as Sessionstorage, but the data will persist after the browser is closed

Api

The usage of sessionstorage and localstorage is basically consistent, and the value of the reference type is converted to JSON

1. Save data to Local
Const INFO = {        name: ' Lee ',        age:20,        ID: ' 001 '    };    Sessionstorage.setitem (' key ', json.stringify (info));    Localstorage.setitem (' key ', json.stringify (info));

  

2. Getting data from local storage
    var data1 = json.parse (Sessionstorage.getitem (' key '));    var data2 = json.parse (Localstorage.getitem (' key '));

  

3. Delete a saved data from the local store
    Sessionstorage.removeitem (' key ');    Localstorage.removeitem (' key ');
4. Delete all saved data
    Sessionstorage.clear ();    Localstorage.clear ();

  

5. Monitor changes to local storage

Storage changes (add, update, delete) when the trigger, the same page changes will not trigger, will only listen to the same domain name other page changes 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);    })

  

Browser viewing methods
      1. Go to Developer tools
      1. Select Application
      1. View the Local Storage and Session Storage under the left Storage

Combining React to realize local storage of user's basic data

Interface UI is not shown, write two components: <Login/> responsible for login input validation; <Home/> Project homepage, show user information

1. Requirements
    • <Login/>The component can get the user input account number, the password, sends the request to the server to obtain{id:‘‘,name:‘‘,tel:‘‘}
    • This data is <Home/> necessary for the component to display correctly, or it will jump to the login page
    • We need to let users open the homepage directly to show the user information, do not jump to the landing page
2. Implement
    • After the user fills in the login information, the login data is stored localStorage in the
    • Enter the homepage, first get the localStorage data in, there is data in the direct display, otherwise enter the login page
1. The login data is stored in localStorageIn

When you configure a function to leave a page in the login page route, the stored data is valid for one hour

    <route path= "Login" Component={login} onleave={leaveloginpage}/>

  

     Import store from '. /store/index ';    Login page Left logic    export const Leaveloginpage = () + {       //Leave login page update localstorage in data       const {ID, name , Tel} = store.getstate (). Rootreducer;       Const USERINFO = {ID, name, tel};       Const USERINFOSTATE = Localstorage.getitem (' userinfostate ');       if (userinfostate) {          //If there is a local userinfostate remove it          localstorage.removeitem (' userinfostate ');       }       Localstorage.setitem (' Userinfostate ', json.stringify ({          userInfo,          timestamp:new Date (). GetTime ()       } ));    }

  

2. Go to the homepage to get localStorageThe data

To configure the go to page handler function in the home route

    <route path= "Home" Component={home} onenter={enterhomepage}>

  

    Import store from '.    /store/index '; The show page enters logic export const Enterhomepage = (nextstate, replace, next) = {Const Rootstate = store.getstate (       ). Rootreducer;       Const USERINFOSTATE = json.parse (Localstorage.getitem (' userinfostate '));  Determine if there is user login data in store if (!rootstate.islogin) {//does not contain user login data, determine if the data in Localstorage can use const PASS = Userinfostate && userinfostate.timestamp && new Date (). GetTime ()-Userinfostate.timestamp <= 60 * 6          0 * 1000; if (pass) {//Userinfostate exists and last left within one hour, can read localstorage data const STOREDUSERINFO = UserInfo             State.userinfo;             ' Login ' will update the acquired data to store Store.dispatch ({type: ' Login ', msg:storeduserinfo});          Next ();             } else {//userinfostate does not exist or has expired, jump to the login page replace ('/login ');          Next ();       }} else {//store contains user login data, go directly to the corresponding page next (); }   } 

  

Web Local Storage (localstorage, sessionstorage)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.