简体   繁体   English

重定向到React中的登录页面

[英]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. 要保持此状态(假设您正在开发Web应用程序),必须使用浏览器存储选项之一保存用户的登录状态。

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 Obs:这是一个JavaScript问题,而不是React.js问题

I am using LocalStorage when I make a redirect about login. 我对登录进行重定向时使用的是LocalStorage

I just stored login data to LocalStorage . 我只是将登录数据存储到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 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];
    }
  }
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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