[React] Lazy load

290 阅读1分钟

今天跟同事探讨怎么写Lazy load,我说我写了个promise 搞定了,他说一行简简单单就行。研究了一下发现,原来React 16.6 出了一个非常优雅的 React.lazy 函数

React 16.6 + Typescript 

import React, { FunctionComponent, Suspense } from 'react';

const Pages: FunctionComponent<{}> = (props) => {
    const Page1:FunctionComponent = React.lazy(() => import('./Page1'));

    // Output --------------------------------------------------------------
    return (
        <>
            <h1 style={styles}>Hello React 16.8</h1>
            <Suspense fallback={<div>loading (show spinner here) ...</div>}>
                <Page1 />
            </Suspense>
        </>
    );
};

export default Pages;

React 16.3 以前的

// build a Lazy.js, after 16.6, you don't have to write this Lazy by yourself

import React from 'react';
const Lazy = (ComponentFunc) => {
    return class extends React.Component {
        state = {
            // component: <Spinner />
            component: null,
        };

        componentDidMount() {
            if (!componentPath) return null;

            // ComponentFunc 是 import(...path), import 返回的是promise,用then 获得import 进来的component
            ComponentFunc().then((myComponent) => {
                this.setState({
                    component: myComponent,
                });
            });
        }

        render() {
            const AsynComponent = this.state.component;
            return AsynComponent ? <AsynComponent {...this.props} /> : null;
        }
    };
};

export default Lazy;

// call LazyComponent
const myComponent = LazyComponent( ()=> import ('./Page1'));

*references: 

zh-hant.reactjs.org/docs/code-s…