react 路由懒加载高阶组件

其实不管是vue还是react,其路由懒加载的实现得益于wepack的异步模块打包,webpack会对代码中异步引入的模块单独打包一份,直到真正调用的时候才去服务端拿。典型的例子就是下面这样一段代码

方法一://lazyLoad.js
import React from 'react';


export default function lazyLoad(componentfn) {
    class LazyloadComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                component: null
            }
        }
        async componentWillMount() {
            const {default: component} = await componentfn();
            this.setState({component})
        }
        render() {
            const C = this.state.component;
            return C ? <C {...this.props}/> : null;
        }
    }
    return LazyloadComponent;
}


//router.js

import React from 'react'
import { Route, HashRouter } from 'react-router-dom'
import lazyLoad from '../common/lazyLoad'

const A = lazyLoad(() => import("../components/a"))
const B = lazyLoad(() => import("../components/b"))
const C = lazyLoad(() => import("../components/c"))
const D = lazyLoad(() => import("../components/d"))

const RouterView = 
<HashRouter>
    <Route path={'/'} component={A} exact={true} key={1} />
    <Route path={'/b'} component={B} exact={true} key={2} />
    <Route path={'/c'} component={C} exact={true} key={3} />
    <Route path={'/d'} component={D} exact={true} key={4} />
</HashRouter>
export default RouterView

 

//index.js

import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import RouterView from './router/router'
ReactDOM.render(
    RouterView,
    document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

 


方法二,react官方提供

//LoadCmp .js

import * as React from 'react';
import Loading from './Loading';

export default function (loader: any) {
    const OtherComponent = React.lazy(loader);
    return function MyComponent(props: any) {
        return (
            <React.Suspense fallback={<Loading />}>
                <OtherComponent {...props} />
            </React.Suspense>
        );
    };
}


//loading.js
import * as React from 'react';

const Loading: React.SFC<any> = () => {
    // return <div>loading...</div>;
    return <div></div>;
};

export default Loading;



例子(用法):
import LoadCmp from './LoadCmp';

<Route key={ 'ProjectHome' } path="/:key" component={ LoadCmp(() => import('../page/Home')) }>

 

 
posted @ 2020-07-09 14:32  清明|雨上  阅读(600)  评论(0)    收藏  举报