1、 项目根目录下新建routes路由文件夹和路由文件index.js,在index.js添加如下代码,用与存放路由、配置路由,分别添加了mainRoutes和adminRoutes模块
import Login from '../pages/Login/Login'; import Wecome from '../pages/Home/Wecome'; import PageNotFound from '../pages/PageNotFound/PageNotFound'; export const mainRoutes = [ { path: '/login', component: Login }, { path: '/404', component: PageNotFound } ] export const adminRoutes = [{ path: '/admin/wecome', component: Wecome }]
2、 项目更目录src\index.js相关代码:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; import {HashRouter as Router, Switch, Route, Redirect} from 'react-router-dom'; import { mainRoutes } from './routes' import App from './App'; ReactDOM.render( <Router> <Switch> <Route path="/admin" render={routeProps=><App {...routeProps} />}/> {mainRoutes.map(route=>{ return <Route key={route.path} {...route}/>; })} <Redirect to="/404"/> </Switch> </Router>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
3、 修改项目根目录app.js下代码,引入adminRoutes代码,用来显示后台相关页面
import React from "react" import { Switch, Route, Redirect } from 'react-router-dom'; import { adminRoutes } from './routes'; 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}/> }} /> })} </Switch> </div> ); } export default App;
4、新建/pages/PageNotFound/,并创建文件PageNotFound.js,做404页面
import React from 'react' function PageNotFound() { return ( <div> <h1>404</h1> </div> ) } export default PageNotFound
上面封装好路由也,如果页面url不存在,则会跳转到404页面。
文章评论(0)