天天看点

react使用react-router-config

react使用react-router-config

下载

npm i react-router-config --save

使用

import { renderRoutes } from 'react-router-config'

1

// App.js

<BrowserRouter>
        <Switch> {renderRoutes(routes.routes)}</Switch>
   </BrowserRouter>           

// router/index.js

import login from '../components/login'

import home from '../components/home'

import message from '../components/message'

export default {

component: login,
routes: [
    {
        path: '/login',
        exact: true,
        component: login
    },
    {
        path: '/',
        component: home,
        routes: [ // 嵌套路由
            {
                path: '/message',
                exact: true,
                component: message,
            }
        ]
    }
]           

}

// matchRouter.js

import matchPath from 'react-router/matchPath'

import Router from 'react-router/Router'

const { computeMatch } = Router.prototype

const matchRoutes = (routes, pathname, branch = []) => {

routes.some((route) => {
    const match = route.path
        ? matchPath(pathname, route)
        : branch.length
            ? branch[branch.length - 1].match
            : computeMatch(pathname)
    if (match) {
        branch.push({ route, match })

        if (route.routes) {
            matchRoutes(route.routes, pathname, branch)
        }
    }

    return match
})

return branch           

export default matchRoutes

// 嵌套路由

// home.js

import React, { Component } from 'react'

const { Header, Sider, Content } = Layout

const SubMenu = Menu.SubMenu;

const MenuItemGroup = Menu.ItemGroup;

const confirm = Modal.confirm;

class Home extends Component{

constructor (props) {
    // 当前路由信息会通过props传递进来,可以打印查看一下
    super(props)
    const {setUser} = props
    this.state = {
        route: props.route.routes
    }
}
render () {
        <div>
            // 使用renderRoutes方法继续渲染子路由
            {renderRoutes(this.state.route)}
        </div>
    )
}           

export default Home

作者:microcosm1994

来源:CSDN

原文:

https://blog.csdn.net/qq_39081974/article/details/93608350

版权声明:本文为博主原创文章,转载请附上博文链接!