react使用react-router-config

下载

npm i react-router-config --save

使用

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

// App.js

{renderRoutes(routes.routes)}

// 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'
import { renderRoutes } from 'react-router-config'

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 () {
			
// 使用renderRoutes方法继续渲染子路由 {renderRoutes(this.state.route)}
) } } export default Home

你可能感兴趣的:(react)