react router config 集中式路由管理(类似于vue-router)

吕飞翼
2023-12-01

1 npm install react-router-config

2 import {renderRoutes, matchRoutes} from 'react-router-config';

3 路由数组

  let routes = [ ];

import Mainlayout from '../page/MainLayout'
import SecondLayout_1 from '../page/SecondLayout_1'
import ThirdLayout_1 from '../page/ThirdLayout_1'
import ThirdLayout_2 from '../page/ThirdLayout_2'
const routesArray = [
    {
        path : "/",
        component : Mainlayout,
        // indexRoute : {component: lddlayout},
        routes : [
            {
                path : "/secondLayout_1",
                component : SecondLayout_1,
                routes : [
                    {
                        path : "/secondLayout_1ThirdLayout_1",
                        component : ThirdLayout_1,
                    },
                    {
                        path : "/secondLayout_1ThirdLayout_2",
                        component : ThirdLayout_2,
                    },
                ]
            }
        ]
    }
]
export default routesArray ;

4

import React from 'react'
import ThirdLayout_1 from '../page/ThirdLayout_1'
import ThirdLayout_2 from '../page/ThirdLayout_2'
import {Link, Route} from "react-router-dom";
import {renderRoutes, matchRoutes} from 'react-router-config';
let Mainlayout = (props)=>{

    return(<div>
        Mainlayout 
        <Link to="/secondLayout_1">secondLayout_1</Link>
        //addition是传给子路由的额外参数 
        {renderRoutes({props.route.routes},{addition:"xxxx"})}
    </div>);
}
export default Mainlayout ;

 

 renderRoutes每次只渲染路由数组中的一层

每次有子路由时都需要使用,会传当前路由的子路由,按需加载,
不是一次性吧所有路由都渲染出来

import { BrowserRouter } from 'react-router-dom'
import { routesArray } from './routerArray'
import {renderRoutes, matchRoutes} from 'react-router-config';

function root() {
  return (
    <BrowserRouter>
      
      {renderRoutes(routesArray )}
    </BrowserRouter>
  )
}

export default root

import React from 'react'
import ThirdLayout_1 from '../page/ThirdLayout_1'
import ThirdLayout_2 from '../page/ThirdLayout_2'
import {Link, Route} from "react-router-dom";
import {renderRoutes, matchRoutes} from 'react-router-config';
let SecondLayout_1 = (props)=>{

    return(<div>
        SecondLayout_1
        <Link to="/secondLayout_1/ThirdLayout_1">ThirdLayout_1</Link>
        <Link to="/secondLayout_1/ThirdLayout_2">ThirdLayout_2</Link>
        //addition是传给子路由的额外参数 
        {renderRoutes({props.route.routes},{addition:"xxxx"})}
    </div>);
}
export default SecondLayout_1;

 类似资料: