react 路由 登录认证管理

案例描述

启动的Root组建
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import route from '../route';
import DevTools from './DevTools';
import { HashRouter as Router } from 'react-router-dom';

export default class Root extends Component {
  render() {
    const { store } = this.props;
    if (!this.route) this.route = route;
    return (
      <Provider store={store}>
        <div>
          <Router children={this.route}/>
          <DevTools />
        </div>
      </Provider>
    );
  }
}
路由配置文件
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';

import Layout from '../views/Layout';
import Login from '../views/Login';
import Register from '../views/Register';
import LoginIn from '../views/LoginIn';

import Home from '@/views/Home';
import Form from '@/views/Form';
import Table from '@/views/Table';
import Calendar from '@/views/Calendar';
import Timeline from '@/views/Timeline';
import Steps from '@/views/Steps';
import Cards from '@/views/Cards';
import Mailbox from '@/views/Mailbox';
import Page2 from '@/views/Page2';

export const childRoutes = [
  {
    'path':'/home',
    'component': Home,
    'exactly': true
  },
  // {
  //   'path':'/loginin',
  //   'component': Home,
  //   'exactly': true
  // },
  {
    'path':'/form',
    'component': Form
  },
  {
    'path':'/table',
    'component': Table
  },
  {
    'path':'/calendar',
    'component': Calendar
  },
  {
    'path':'/timeline',
    'component': Timeline
  },
  {
    'path':'/steps',
    'component': Steps
  },
  {
    'path':'/cards',
    'component': Cards
  },
  {
    'path':'/mailbox',
    'component': Mailbox
  },
  {
    'path':'/page2',
    'component': Page2
  }
];

const routes = (
  <Switch>
    <Route path="/login" component={Login}/>
    <Route path="/loginin" component={LoginIn}/>
    <Route path="/register" component={Register}/>
	{/* 一定要放在最后,前面的都匹配不成功,才会匹配根路径 */}
    <Route path="/" component={Layout}/>
  </Switch>
);

export default routes
  1. “/” 根路由匹配放到最后,前面匹配不成功,则匹配根目录
  2. Layout是验证是否登录的的组件
Layout登录成功之后的组件
import React from 'react';
import PropTypes from 'prop-types'
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {Layout, Affix , Row, Col} from 'antd';
import { Route, Redirect } from 'react-router-dom';

import { childRoutes } from '@/route'
import authHOC from '@/utils/auth'

import NavPath from '@/components/NavPath'
import Header from '@/components/Header'
import Sidebar from '@/components/Sidebar'
import Footer from '@/components/Footer'
import {fetchProfile, logout} from '@/actions/auth';

import './index.less';

const { Content } = Layout;

class Layout extends React.Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    const {actions} = this.props;
    actions.fetchProfile();
  }

  render() {
    const {auth, navpath, actions} = this.props;

    return (
      <Layout className="ant-layout-has-sider">
        <Sidebar />
        <Layout>
          <Header profile={auth} logout={actions.logout} />
          <Content style={{ margin: '0 16px' }}>
            <NavPath data={navpath} />
            <div style={{ minHeight: 360 }}>
				{/* 登录成功之后,直接重定向到/home 路由,然后显示/home 路由的组件 */}
              <Redirect to="/home"/>
              {childRoutes.map((route, index) => (
                <Route key={index} path={route.path} component={authHOC(route.component)} exactly={route.exactly} />
              ))}
            </div>
          </Content>
          <Footer />
        </Layout>
      </Layout>
    );
  }
}

Layout.propTypes = {
  auth: PropTypes.object,
  navpath: PropTypes.array
};

const mapStateToProps = (state) => {
  const { auth, menu } = state;
  return {
    auth: auth ? auth : null,
    navpath: menu.navpath
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({fetchProfile, logout}, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Layout);
authHOC 验证是否登录的方法
import React, { Component } from "react";
import { withRouter } from "react-router-dom";

const validate = function(history) {
  const isLoggedIn = !!window.localStorage.getItem("uid");
  if (!isLoggedIn && history.location.pathname != "/login") {
    history.replace("/login");
  }
};

/**
 * Higher-order component (HOC) to wrap restricted pages
 */
export default function authHOC(BaseComponent) {
  class Restricted extends Component {
    componentWillMount() {
      this.checkAuthentication(this.props);
    }
    componentWillReceiveProps(nextProps) {
      if (nextProps.location !== this.props.location) {
        this.checkAuthentication(nextProps);
      }
    }
    checkAuthentication(params) {
      const { history } = params;
      validate(history);
    }
    render() {
      return <BaseComponent {...this.props} />;
    }
  }
  return withRouter(Restricted);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值