1. Introduce the store.js library

The project address

npm i store
Copy the code

2. Define and export the storage to the local module (storageutils.js)

/ /! This module is mainly for local data storage
import store from 'store'
const USER_KEY = 'user_key';

export default {
    // Save the user
    saveUser(user) {
        store.set(USER_KEY,user);// Upon successful login, the user data is read and stored in memory
            const user = result.data;
            // memoryUtils.user = user;
            storageUtils.saveUser(user);
    },

    // Read the user
    getUser() {
        return store.get(USER_KEY) || {}
    },

    // Delete the user
    removeUser(){ store.remove(USER_KEY); }}Copy the code

3. When the login succeeds, the user data is saved in the saveUser method of storageUtils

// On successful login, read user data and put it in memory // Save local user to memory
const user = storageUtils.getUser();
memoryUtils.user = user;
const user = result.data;
// memoryUtils.user = user;
storageUtils.saveUser(user);
Copy the code

4. Define memory files that record user information (memoryutils.js)

/ /! This file stores the user information to be stored
export default {
    user: {}}Copy the code

5. In the entry file, save the user information in local to the memory file

// Save the user from local to memory
const user = storageUtils.getUser();
memoryUtils.user = user;
Copy the code

6. After the login is successful, the page checks whether there is a user in the memory file. If yes, the memory file is loaded

const user = memoryUtils.user;
// If no user ID is obtained, return to the login page
if(! user._id) {return <Redirect to='/login' />
}
Copy the code