1. 程式人生 > >前端進階(五)react分路由打包

前端進階(五)react分路由打包

1、AsyncCommponent.js

import React, { Component } from "react";

export default (importComponent) => {
    class AsyncComponent extends Component {
        constructor(props) {
            super(props);

            this.state = {
                component: null
            };
        }

        async componentDidMount() {
            const { default: component } = await importComponent();

            this.setState({
                component: component
            });
        }

        render() {
            const C = this.state.component;

            return C ? <C {...this.props} /> : null;
        }
    }

    return AsyncComponent;
}

2、每個專案的router

import asyncComponent from '../../components/AsyncComponent';

const view = asyncComponent(() =>
    import ( /* webpackChunkName: "mind.map" */ './MindMapApp'));
const share = asyncComponent(() =>
    import ( /* webpackChunkName: "mind.map_share" */ './MindMapShare'));
const chart = asyncComponent(()=>
    import(/*webpackChunkName: "mind.map_chart"*/ './MindMapChart'));
const demo = asyncComponent(()=>
    import(/*webpackChunkName: "mind.map_chart"*/ './MindMapDemo'));

const routes = [
    {
        path: '/mind.map/share',
        component: share
    },
    {
        path: '/mind.map/chart/:nodeid',
        component: chart
    },
    {
        path: '/mind.map/demo',
        component: demo
    },
    {
        path: '/mind.map/:code',
        component: view
    },
    {
        path: '/mind.map',
        component: view
    }
];

export default routes;

3、在App.js中匯入router中的所有router,併合並所有路由

import React, {Component} from 'react';
import {HashRouter as Router, Switch} from 'react-router-dom';
import {renderRoutes} from 'react-router-config';
import csr_v2_routes from './routes/csr.v2/router';
import f9OptionRouter from './routes/f9.option/router';
import ovs_routes from './routes/ovs/router';
import mindMapRouter from './routes/mind.map/router';
/**
 * 合併各專案路由
 */
const routes = [
    ...csr_v2_routes,
    ...f9OptionRouter,
    ...ovs_routes,
    ...mindMapRouter,
];

class App extends Component {
    render() {
        return (
            <Router>
                <Switch>
                    {renderRoutes(routes)}               
                </Switch>
            </Router>
        );
    }
}


export default App;