路由表文件 RouterConfig.js
import Home from '../pages/Home'
import Login from '../pages/Login'
import Detail from '../pages/Detail'
// 二级路由
import Classify from '../pages/home/Classify'
import Car from '../pages/home/Car'
import My from '../pages/home/My'
import Vip from '../pages/home/Vip'
export default [
{
from: "/",
to: "/home"
},
{
path: "/home",
com: Home,
children: [
{
from: "/home",
to: "/home/classify"
},
{
path: "/home/classify",
com: Classify,
title: "分类"
},
{
path: "/home/car",
com: Car,
title: "购物车"
},
{
path: "/home/my",
com: My,
title: "我的"
},
{
path: "/home/vip",
com: Vip,
auth: true,
title: "vip"
}
]
},
{
path: "/login",
com: Login
},
{
path: "/detail",
com: Detail
}
]
路由组件 RouterView.jsx
import React, { Component } from 'react'
import { Route, Redirect, Switch } from 'react-router-dom'
export default class RouterView extends Component {
render() {
const { routerList } = this.props
// 过滤出重定向的数据
let RedirectList = routerList.filter(item => item.to)
// 过滤出展示视图的数据
let List = routerList.filter(item => !item.to)
return (
<React.Fragment>
<Switch>
{
List.map((item, index) => {
return <Route path = { item.path } render = {() => {
let Com = item.com
// 判断是否需要拦截
if (item.auth && !sessionStorage.getItem('token')) {
// to = "" to = {}
return <Redirect to={{
pathname: "/login",
from: item.path
}}/>
}
// 判断是否要传递children
if (item.children) {
return <Com children = { item.children }/>
} else {
return <Com/>
}
}} key = { index }/>
})
}
{/* 重定向的 */}
{
RedirectList.map((item, index) => {
return <Redirect from = { item.from } to = { item.to } key = { index }/>
})
}
</Switch>
</React.Fragment>
)
}
}
展示组件:
import RouterList from './RouterConfig'
<RouterView routerList = { RouterList }/>
<RouterView routerList = { this.props.children }/>