封装路由表
import React, { Component } from 'react';
import {Switch, Route, Redirect} from 'react-router-dom';
class RouterView extends Component {
render() {
let {routes} = this.props;
let rdArr = routes.filter(item=> item.redirect);
let rdCom = rdArr.map((item,key)=><Redirect from={item.path} to={item.redirect} key={key} />);
return (
<Switch>
{
routes.map((item,key)=> !item.redirect && <Route path={item.path} key={key} render={(props)=><item.component {...props} routes={item.children} />} />).concat(rdCom)
}
</Switch>
);
}
}
export default RouterView;
调用
import RouterView from './router/RouterView';
import routes from './router/routerConfig';
<RouterView routes={routes.routes} />
路由表格式
routes: [
{
path: '/home',
component: Home
},
{
path: '/index',
component: Index,
children: [
{
path: '/index/hot',
component: Hot
},
{
path: '/index/cold',
component: Cold
},
{
path: '/index',
redirect: '/index/hot'
}
]
},
{
path: '/',
redirect: '/index'
}
]