react脚手架项目,根据 localstorage 判断用户是否登录

本地存储 localstorage 判断用户是否登录

APP.js


import React, { Component } from 'react';

import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom";

import Login from './pages/login';

import Home from './pages/home';


class App extends Component{

  state = {
    userInfo: {}
  };

  componentWillMount() {
    // 获取localstorage
    let userInfo = localStorage.getItem("userInfo");
    // 判断用户是否登录/登录信息是否过期
    if(userInfo && Date.now() - JSON.parse(userInfo).date < 2 * 60 * 60 * 1000) {
      this.setState({userInfo: JSON.parse(userInfo)});
    }
  }

  render() {
    const { userInfo } = this.state;
    let { search } = window.location;
    return (
        <BrowserRouter>
          <Switch>
            <Route path="/login" render={() => 
              Object.keys(userInfo).length > 0 
              ? <Redirect to={
                search 
                ? decodeURIComponent(search.split("=")[1]) 
                : "/"
              } /> 
              : <Login />
            } />
            <Route path="/" render={() => (
              Object.keys(userInfo).length > 0 
              ? <Home />
              : <Redirect to={"/login?redirect=" + encodeURIComponent(window.location.pathname)} />
            )} />
          </Switch>
        </BrowserRouter>
    );
  }
}

export default App;

login/index.jsx


import React, {Component} from 'react';
import {Input, Icon, message} from 'antd';

class Login extends Component {
  constructor(props) {
    super(props);
    this.login = this.login.bind(this);
    this.state = {
      loginInfo: {
        username: "",
        password: ""
      },
      redirect_url: ""
    }
  }

  componentDidMount() {
    const { search } = window.location;
    const redirect_url = search ? decodeURIComponent(search.split("=")[1]) : "/";
    this.setState({redirect_url});
  }

  render() {
    const { loginInfo } = this.state;
    return (
      <div className="login-bg">
        <div className="login-form-wrapper">
          <div className="login-form">
            <h4 className="login-title">登录</h4>
            <Input
              value={loginInfo.username}
              size="large"
              onChange={e => this.changeInputValue(e.target.value, "username")}
              prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)', marginRight: 10}}/>}
              style={{marginBottom: 30}}
              placeholder="用户名"
            />
            <Input
              value={loginInfo.password}
              size="large"
              type="password"
              onChange={e => this.changeInputValue(e.target.value, "password")}
              prefix={<Icon type="lock" style={{color: 'rgba(0,0,0,.25)', marginRight: 10}}/>}
              placeholder="密码"
            />
            <div className="login-btn cursor" onClick={this.login}>登录</div>
          </div>
        </div>
      </div>
    )
  }

  changeInputValue(value, name) {
    const { loginInfo } = this.state;
    loginInfo[name] = value;
    this.setState(state => ({loginInfo: {...state.loginInfo, ...loginInfo}}))
  }

  login() {
    const { loginInfo, redirect_url } = this.state;
    if(!loginInfo.username 
      || !loginInfo.password 
      || (loginInfo.username !== "admin"
        && loginInfo.password !== "123456")) return message.error("用户名或密码输入有误");
    loginInfo.date = new Date().getTime();
    const userInfo = JSON.stringify(loginInfo);
    localStorage.setItem("userInfo", userInfo);
    window.location.href = redirect_url;
    this.setState({loginInfo: {}, redirect_url: ""});
    message.success("登录成功")
  }
}

export default Login;
    原文作者:weblixin
    原文地址: https://segmentfault.com/a/1190000019816000
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞