• react--路由封装


    路由封装流程

    • 封装路由的文件组件 ,针对一级路由的封装操作,单独路由文件抽离出单独的文件中去

    • src中新建一个router文件夹,在文件夹新建index.js文件,路由配置文件迁移过去

    • router文件夹中新建mapRouter文件,路由配置转换成数组对象格式,参考Vue配置

    • index.js循环Route组件即可,二级路由配置先暂时在父组件中配置即可

    注:文件夹的名称和文件的名字可以随便定义,无需完全按照上方流程来

    index.js

    1. import { default as React } from 'react';
    2. import ReactDOM from 'react-dom/client';
    3. import './index.css';
    4. import reportWebVitals from './reportWebVitals';
    5. import {Routes} from '../src//router/index'
    6. const root = ReactDOM.createRoot(document.getElementById('root'));
    7. root.render(
    8. <Routes/>
    9. );
    10. reportWebVitals();

    router/index.js

    1. //router/index.js文件
    2. import { HashRouter as Router, Route, Switch } from "react-router-dom"
    3. import routes from './mapRoute';
    4. //定义的路由函数直接挂载到主页面上去
    5. const Routes = function () {
    6. console.log(routes);
    7. return (
    8. <Router>
    9. <Switch>
    10. {
    11. routes.map((item,index)=>{
    12. return (
    13. <Route key={index} path={item.path} component={item.component}>Route>
    14. )
    15. })
    16. }
    17. Switch>
    18. Router>
    19. )
    20. }
    21. export default Routes;

     HashRouter as Router,这是给HashRouter起的别名,可以不写

    router/mapRoute.js路由配置文件

    1. import App from '../App';
    2. import Detail from '../detail';
    3. import Layout from "../admin/layout"
    4. import About from '../pages/About';
    5. const routes = [
    6. {
    7. path:"/about",
    8. title:"About",
    9. component:About,
    10. },
    11. {
    12. path:"/admin",
    13. title:"管理后台",
    14. component:Layout,
    15. exact:false,
    16. },{
    17. path:"/detail/:id",
    18. title:"detail",
    19. component:Detail,
    20. },{
    21. path:"/",
    22. title:"App",
    23. component:App,
    24. }
    25. ]
    26. export default routes;

    这样我们react中的路由就封装好了,他的原理是跟我们vue中的路由一样,把路由封装到一个文件中,然后我们就可以直接在这个里面添加路由,不同的是,vue中有一个children属性用来定义二级路由,而react中没有

    我们在这个js文件中引入路由,然后在index文件中进行循环渲染,同时也减少了我们的代码量

    不过需要注意的是,我们在react路由封装中不能使用二级路由,这是一个弊端,我们可以将二级路由定义在父组件中定义

  • 相关阅读:
    若依框架解读(前后端分离版)—— 1.Spring Security相关配置(@Anonymous注解)
    springboot项目Html页面引入css文件不生效
    怎样用图片去搜索商品呢?
    全球化浪潮下的技术与安全
    Kotlin 语言基础学习
    (附源码)spring boot球鞋文化交流论坛 毕业设计 141436
    Zookeeper常见命令
    Linux上文本处理三剑客之grep
    mybatis缓存-二级缓存
    二叉树题目:奇偶树
  • 原文地址:https://blog.csdn.net/qq_60976312/article/details/126181600