简体   繁体   中英

Redirect to the login page in React

我有一个Redux存储一个当前登录的用户。刷新页面时,状态丢失了,我想做的就是刷新任何要重定向到登录页面的组件时,该如何做。我能做到吗?

Your Store state will be lost whenever you refresh the page. To persist this state, assuming that you are developing a web application, you must use one of the browser storage options to save the user̈́'s logged state.

Short Example:

// Setting the user info to the local storage
    localStorage.setItem('userId', 'Logged');

// Retrieving the information before rendering the route component
var userInfo = localStorage.getItem('userId');

Please, refer for this link to a full example.

Obs: This is a JavaScript problem, not a React.js problem

I am using LocalStorage when I make a redirect about login.

I just stored login data to LocalStorage .

Main Page Component

import React from 'react';
import { Redirect } from 'react-router-dom';
import storage from 'lib/storage';

const MainPage = () => {
  function redirect(){
    if(storage.get('user')){
      return <Redirect to="/login" />
    }else{
      return null;
    }
  }

  return (
    <main>
      {redirect()}
      /* ... */
    </main>
  )
}

lib/storage.js

export default (function () {
  const st = localStorage || {};
  return {
    set: (key, object) => {
      const arr = [];
      arr.push(JSON.stringify(object));
      st[key] = arr;
    },
    add: (key, object) => {
      let old = st.getItem(key);
      if (old === null) old = '';
      st.setItem(key, old + ((typeof object) === 'string' ? object : JSON.stringify(object)));

    },
    get: (key) => {
      if (!st[key]) {
        return null;
      }
      const value = st[key];

      try {
        const parsed = JSON.parse(value);
        return parsed;
      } catch (e) {
        return value;
      }
    },
    remove: (key) => {
      if (localStorage) {
        return localStorage.removeItem(key);
      }
      delete st[key];
    }
  }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM