React路由封装、404页面设置

2021-08-14   阅读:250   分类:前端    标签: React

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页面。

【腾讯云】爆款1核2G云服务器首年48元,还有iPad Pro、Bose耳机、京东卡等你来抽!

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://www.tpxhm.com/fdetail/776.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸 头像

简忆博客
勤于学习,乐于分享。

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×