react-router4 路由集中式配置

react-router自版本4开始,发生了很大的变化,其中一点就是,开始倡导组件式使用,不再支持集中式的配置,而出于开发的习惯以及便于项目路由的管理,还是有许多地方希望可用使用集中式的方式来配置路由。下面介绍一种实现方式。

router.js

使用import()实现按需加载

import React, {Component} from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import CompileComponent from './compile-component.js'

const router = [
    {
        path: '/',
        redirect: '/0',
    },
    {
        path:'/0',
        loader: () => import('@/containers/page'),
        childRoutes: [
            {
                path: '/0/1',
                loader: () => import('@/containers/page1')
            }
        ]
    },
    {
        path:'/2',
        loader: () => import('@/containers/page2'),
    }
];

export default class Router extends Component {
    compileRoutes = ({path, redirect, name, loader, childRoutes}, key) => {
        if(Array.isArray(childRoutes)) {
            let routes = childRoutes.map((route, index) => this.compileRoutes(route, index, path));
            return (
                 {
                    if (redirect) {
                        return ();
                    }
                    return (
                            
                        );
                }}/>                
            )
        }

        return (
             {
                if (redirect) {
                    return ();
                }
                return ();
            }}/>
        )
    }

    

    render() {
        return (
            
                
                    {
                        router.map((route, key) => this.compileRoutes(route, key))
                    }
                
            
        );
    }
}

compile-component.js

import React, { Component } from 'react';

export default class CompileComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loaded: false,
            C: null
        };
    }

    componentDidMount() {
        this.compileComponent();
    }

    compileComponent = async () => {
        const { loader } = this.props;
        loader().then((value) => {
            this.setState({
                C: value.default,
                loaded: true
            });
        });
    }

    render() {
        const { loaded, C } = this.state;
        const {routes} = this.props;
        return (
            
{ loaded && { routes } }
); } }

index.js

import React from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import ReactDOM from 'react-dom';
import Router from './router.js';

ReactDOM.render(
        ,
    document.getElementById('root')
);

*仅做参考,实际使用,需根据项目自行调整

你可能感兴趣的:(React)