具体思路:
通过配置一个路由表,在路由信息中添加一个字段来判断是否被拦截。
通过写js操作来判断是否有这个字段。
如果有则通过重定向进行拦截。
下面看代码:
主页:
import React, { Component } from 'react'
import MyView from './MyView'
import routerList from './routerConfig'
export default class index extends Component {
render() {
return (
<div className="layOut">
<MyView list = { routerList }/>
</div>
)
}
}
路由表:
import Home from '../components/Home'
import Detail from '../components/Detail'
import Login from '../components/Login'
import List from '../components/List'
import Car from '../components/Car'
import My from '../components/My'
let routerList = [
{
to: '/home',
com: Home,
children: [
{
to: '/home/list',
com: List,
title: '列表'
},
{
to: '/home/car',
com: Car,
title: '购物车',
auth: true
},
{
to: '/home/my',
com: My,
title: '我的',
auth: true
},
{
to: '/home/list',
from: '/home'
}
]
},
{
to: '/detail',
com: Detail
},
{
to: '/login',
com: Login
},
{
to: '/home',
from: '/'
}
]
export default routerList
路由判断:
import React, { Component } from 'react'
import { Route, Switch, Redirect } from 'react-router-dom'
export default class MyView extends Component {
render() {
let { list } = this.props
// 筛选非重定向的数据
let newList = list.filter(item => !item.from)
// 筛选重定向的数据
let redirect = list.filter(item => item.from)
return (
<Switch>
{
newList.map((item, index) => {
let Com = item.com
return <Route path = { item.to } key = { index } render = { (prop) => {
//判断是否要进行重定向,并且是不是登录页面
if (item.auth && !sessionStorage.getItem('isLogin')) {
return <Redirect to = {{
pathname: "/login",
params: {
path: item.to
}
}}/>
}
if (item.children) {
return <Com child = { item.children } navList = { item.children.filter(item => !item.from) } {...prop} />
} else {
return <Com {...prop} />
}
}}/>
})
}
{
redirect.map((item, index) => {
return <Redirect key = { index } from = { item.from } to = { item.to }/>
})
}
</Switch>
)
}
}