路由文件及其使用

1、新建路由文件,根據路由的不同作用,劃分成不同模塊
	export const mainRoutes=[
		{
		    path:'/x',
		    component:X,
		    exact:true   如果需要精確匹配
		},
		{
		    path:'/x',
		    component:X
		}
	]
	export const otherRoutes=[
			...
	]
	
2、構建路由:
	index.js放置如登錄等的入口路由
	App.js放置登錄後的主要內容路由
	路由文件中的屬性通過map遍歷來生成路由,使用{...item}解構將所有屬性放在<Route />內

代碼示例:
routes下的index.js:

import Login from '../pages/login'
import Index from '../pages/admin/dashboard/index'
import List from '../pages/admin/products/list'
import Edit from '../pages/admin/products/edit'
import PageNotFound from '../pages/PageNotFound'

export const mainRoutes=[{
    path:'/login',
    component:Login
},
{
    path:'/404',
    component:PageNotFound
}
]

export const adminRoutes=[{
    path:'/admin/dashboard',
    component:Index
},
{
    path:'/admin/products',
    component:List,
    exact:true
},
{
    path:'/admin/products/edit/:id',
    component:Edit
}
]

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import {HashRouter,Switch,Route,Redirect} from 'react-router-dom'
import './index.css';
import * as serviceWorker from './serviceWorker';
import App from './App';
import {mainRoutes} from './routes/index';

ReactDOM.render(
  <HashRouter>
      <Switch>
        <Route path='/admin' render={routeProps=><App {...routeProps}></App>}></Route>
       {mainRoutes.map(route=>{
         return <Route key={route.path} {...route}></Route>
       })}
       <Redirect to='/404'></Redirect>
      </Switch>
  </HashRouter>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

App.js

import React from 'react';
import './App.css';
import {Switch,Route,Redirect} from 'react-router-dom'
import {Button} from 'antd'
import 'antd/dist/antd.css'
import {adminRoutes} from './routes/index'

function App() {
  return (
    <div className="App">
      <h1>app</h1>
      <Switch>
        {adminRoutes.map(route=>{
          return <Route  key={route.path} path={route.path} exact={route.exact} render={routeProps=>{
            return <route.component {...routeProps}></route.component> 
          }}></Route>
        })}
        <Redirect to='/404'></Redirect>
      </Switch>
    </div>
  );
}

export default App;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章