React模拟后台项目(四)路由文件配置

一、路由封装 src/router/privateRoute.js

// 导入react全家桶
import React from 'react'
import { Route, Redirect } from 'react-router-dom'

// 手册:https://reacttraining.com/react-router/web/example/auth-workflow
  
// 自定义私有路由高阶组件
const PrivateRoute = ({component: Component, ...props}) => {
    // 解构赋值 将 props 里面的 component 赋值给 Component
    return <Route {...props} render={() => {
        const token = localStorage.getItem('token' )
        if (token){ // 如果登录了, 返回正确的路由
            return <Component />
        } else { // 没有登录就重定向至登录页面
            return <Redirect to='/login' /> 
        }
    }}/>
}

// 导出
export default PrivateRoute

二、配置路由 src/router/index.js

// 导入库
import React,{Component} from 'react';
import {
    BrowserRouter as Router,
    Route,
    Switch,
    Redirect
} from 'react-router-dom'; 
import PrivateRoute from './privateRoute'

// 导入组件
import Login from '../pages/login/index';
import LayoutFrom from '../components/frame/index'; // 侧边栏
import Admin from '../pages/admin/index'; // 首页
import Users from '../pages/users/index'; // 用户列表
import UsersCreate from '../pages/users/usersCreate/index' // 添加用户
import Err404 from '../components/err/404';
import Err500 from '../components/err/500';

class ReactRouter extends Component
{
    render()
    {
        return (
            <Router>
                <Switch>
                    <Route path="/" exact component={Login}/>
                    <Route path="/login" component={Login}></Route>
                    <Route path="/admin">
                    <LayoutFrom>
                        <Switch>
                            {/* 
                            备注:后期这里有很多很多路由
                            举例:订单路由、商品路由等
                            */}              
                            {/* <PrivateRoute path="/admin" exact component={Admin}/>
                            <PrivateRoute path="/admin/users" exact component={Users}/>
                            <PrivateRoute path="/admin/users/create" component={UsersCreate}/> */}
                            <Route path="/admin" exact component={Admin}/>
                            <Route path="/admin/users" exact component={Users}/>
                            <Route path="/admin/users/create" component={UsersCreate}/>
                        </Switch>
                    </LayoutFrom>
                    </Route>
                    <Route path="/404" component={Err404}></Route>
                    <Route path="/500" component={Err500}></Route>
                    <Redirect to="/404" /> 
                </Switch> 
            </Router>
        )
    } 
}

export default ReactRouter;

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页