添加react-router
1、index.js 内容:
import React from 'react' import ReactDOM from 'react-dom' import { renderRoutes } from 'react-router-config' import { BrowserRouter } from 'react-router-dom' import routes from './js/routes' import './index.css' import registerServiceWorker from './registerServiceWorker' ReactDOM.render(( <BrowserRouter> {renderRoutes(routes)} </BrowserRouter>), document.getElementById('root')) registerServiceWorker()
2、routes.js 内容
/** * Created by Administrator on 2017/12/20. */ import Root from './Root'; import Home from './containers/Home' import ManagerHome from './containers/ManagerHome' import StaffHome from './containers/StaffHome' import Login from './containers/Login' const routes = [ { component: Root, redirect: '/home', routes: [ { path: '/home', // exact: true, component: Home, routes: [ { path: '/home/ManagerHome', component: ManagerHome, }, { path: '/home/StaffHome/:id', component: StaffHome, }, ] }, { path: '/Login', component: Login, } ] } ]; export default routes;
3、Root.js :
/** * Created by Administrator on 2017/12/20. */ import React, {Component} from 'react'; import {renderRoutes} from 'react-router-config'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import '../images/font/iconfont.css' import './Root.css' class Root extends Component { render(props) { console.log('------>Root'); let {route} = this.props; return ( <MuiThemeProvider id="root" className="homeDiv"> {/* child routes won't render without this */} {renderRoutes(route.routes)} </MuiThemeProvider> ) } } export default Root;
4、Home.js (子路由):
/** * Created by Administrator on 2017/12/20. */ import React, {Component} from 'react'; import homeService from '../service/homeService'; import {renderRoutes} from 'react-router-config' class Home extends Component { constructor(props) { super(); this.checkAuth(); } checkAuth() { homeService.checkAuth().then(res => { if (res.ispassed) { let user = res.info; if (user.type == '1') this.props.history.push('/home/ManagerHome') else this.props.history.push('/home/StaffHome/'+user.id) } else this.props.history.push('/Login') }) } render() { let {route} = this.props; return ( <div> {renderRoutes(route.routes, {someProp: 'these extra props are optional'})} </div> ) } } export default Home;