Local storage local storage use

Keywords: React axios less

Store data
localStorage.setItem("name","Amy") //Store the variable with name and Amy
localStorage.name = "Amy"; // Equivalent to the above command
localStorage // Storage{name: "Amy", length: 1} read data
Read data
localStorage.getItem("name") //Amy, read the value of the variable named name stored in the localStorage object
localStorage.name // "Amy"
localStorage.valueOf() //Read all data stored on localStorage
localStorage.key(0) // Read the variable name (key value) of the first data
//Traverse and output the name and value stored in localStorage
for(var
i=0; i<localStorage.length;i++){
  console.log('localStorage No'+i+'The name of the data is:'+localStorage.key(i)+',The value is:'+localStorage.getItem(localStorage.key(i)));
}
So, it's equivalent to having a variable on localstorage or clicking a parameter later. If you simply make localstorage equal to a variable, it's not saved on it
Combined with the concrete use of react project
import React, { Component } from 'react';
var storage=window.localStorage;
class Login extends Component{
    constructor(props){
        super(props);
        this.state={
          userName:"", //User name
          password:""  //Password
        }
    }
    //Request interface
    userOnLine=()=>{
     axios
     .post("/safemgmt/api/admin/login",{
         username:this.state.userName,
         password:this.state.password,
     })  
    .then(res=>{
         if(res.data.code==="0"){
          window.location.href="#/admin/home "/ / click to jump to the component
         }
         storage.token = res.data.result.token;
         axios.interceptors.request.use(function (config) {
          config.withCredentials = true
          config.headers = {
              token : storage.token
          }
          return config;
          }, function (error) {
          return Promise.reject(error);
      })
     })   
    }
 render() {
        <div>
         //content
        </div>
        )}
    }
export default Login;

PS: I'm just a small firewood farmer. I've accumulated experience in the actual combat. I'm just sharing the pit I stepped on with my friends who met the same pit. Maybe I'll take less detours. If it can help you solve practical problems, I will be more determined to share the original intention: grow together.
At present, I only update articles on Zhihu and Jianshu. I'm ready to keep updating articles in these two places. Your attention may be a great encouragement to me.

Zhihu user name: fachai minong
Weibo user name: stubborn patients

Ha ha, make a friend~

Posted by eatc7402 on Mon, 02 Dec 2019 10:59:53 -0800