import Login from '../component/login/index'
import Index from '../component/index/index'
import Props from '../component/props/index'
import Events from '../component/event/index'
export const routes = [
{
path: '/index', // 当前组件的重定向在组件去实现 (见下方实例)
component: Index,
children: [
{
path: '/index/events',
component: Events
},
{
path: '/index/props',
component: Props
}
]
}
]
import { Redirect, useHistory } from 'react-router-dom'
export default function Home (props) {
const { Header, Content, Footer, Sider } = Layout
const History = useHistory()
// 重定到某个页面
const Re = () => {
if (History.location.pathname !== '/index') return null
return <Redirect to="/index/events" />
}
return (
<>
<Re/> // 符合条件就会渲染重定向组件
{props.children} //有组件嵌套就需要
</>
)
index文件是主要展示内容的
import React from 'react';
import { Menu } from 'element-react';
import './index.scss'
// import { CSSTransition } from 'react-transition-group'
import 'element-theme-default';
export default class Index extends React.Component {
render() {
let { routes } = this.props; //取到传进来的路由表
console.log(routes)
return (
<></>)
最终路由展示
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
import { routes } from './routerList'; //路由表
class RouterView extends Component {
render() {
// let { routes } = this.props; //取到传进来的路由表
console.log(routes)
// let rdArr = routes.filter(item => item.redirect); //把所以路由重定向取出来
// let rdCom = rdArr.map((item, key) => <Redirect from={item.path} to={item.redirect} key={key} />);
return (
<Router>
<Switch>
{
routes.map((item, index) => {
if (item.children && item.children.length > 0) {
return (
<Route path={item.path} key={index} render={() => (
<item.component> {
item.children.map((children, childrenKey) => {
return (
<Route path={children.path} key={children.path} component={children.component}></Route>
)
})
}
</item.component>
)} ></Route>
)
} else {
return (
<Route path={item.path} key={index} component={item.component}></Route>
)
}
})
}
<Redirct from='/' to='/login' />
</Switch>
</Router>
);
}
}
export default RouterView;