天天看點

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

版權聲明:本文為部落客原創文章,轉載請附上博文連結!