首先在react项目的src文件夹下创建文件:例:router.view.js和router.config.js
router.config.js---生成并抛出路由配置表
//引入路由试图组件
import Table from "../component/table";
import About from "../component/about";
import Log from "../component/log";
import Login from "../component/login";
import LoginSucceed from "../component/loginSucceed";
import MySy from "../component/table/mySy";
import TuiJ from "../component/table/tuiJ";
import XinX from "../component/table/xinX";
import My from "../component/table/my";
const routers = [
{ //重定向配置
from:'/',
to:'/table'
},
{
path:'/about',
component:About
},
{
path:'/login',
component:Login
},
{
path:'/loginSucceed',
component:LoginSucceed
},
{
path:'/log',
component:Log
},
{
path:'/table',
component:Table,
children:[ //一级路由配置
{
from:'/',
to:'/table/mySy',
children:[ //二级路由配置
{
from:'/', //一级路由重定向
to:'/table/mySy/ErJiRouter'
},
{
path:'/table/mySy/ErJiRouter',
component:ErJiRouter
}
]
},
{
path:'/table/mySy',
component:MySy
},
{
path:'/table/tuiJ',
component:TuiJ
},
{
path:'/table/xinX',
component:XinX
},
{
path:'/table/my',
component:My
},
]
}
]
export default routers
router.config.js 加载路由视图组件大函数
import React, { Component } from 'react'
//引入路由内置组件
import { Switch, Route, Redirect } from 'react-router-dom'
export default class Index extends Component {
render() {
const { routers } = this.props //得路由落配置表
const routerList = routers.filter(item => !item.to) //筛选出不是重定向的路由数据
//筛选是重定向数据并生成
const MyRedirect = routers.filter(item => item.from).map((item, key) => <Redirect key={key} from={item.from} to={item.to}></Redirect>)
return (
<Switch>
{
//生成路由对象 路由组件等
routerList && routerList.map((item, key) => <Route path={item.path} key={key}
//路由嵌套,二级路由 , ...props 二级路由可以获取到props
render={props => <item.component {...props} routers={item.children}></item.component>}
></Route>).concat(MyRedirect) //添加重定向
}
</Switch>
)
}
}
app.js文件下
import React from 'react';
//引入路由配置表
import routers from './router/router.config'
//引入加载路由的组件
//引入加载路由的组件
import MyRouter from './router/router.view'
//引入路由内置组件
//引入路由内置组件
import { BrowserRouter } from 'react-router-dom'
function App() {
return (
<BrowserRouter>
//加载、展示路由试图组件并传入路由配置表
<MyRouter routers={routers}></MyRouter>
</BrowserRouter>
);
}
export default App;
在此需要提醒下,如果路由视图组件写在app.js文件夹下时,每个页面都会存在路由组件
注意:
一、二级路由或三级路由需在对应有路由的组件下引入添加:
import MyRouter from '../../router/router.view'
<MyRouter routers={this.props.routers}></MyRouter>
<NavLink to="路由表对应地址">首页</NavLink>