React自定义组件之懒加载-LazyLoad。

先放上程序,新建一个components。

import React, { Component,lazy,Suspense } from 'react';

export default class Index extends Component {

  constructor(props) {
    super(props);
    this.state = {

    };
  }
  _renderLazy = ()=>{
      let Lazy;
      const {component,delay,...other} = this.props;
      if(!component || component.constructor.name !=='Promise'){
          Lazy = import('./error');
    
      }
      Lazy = lazy(()=>{
          return new Promise(resolve =>{
              setTimeout(()=>{
                  resolve(component);
              },delay||200)
          })
      })
      return <Lazy {...other}/>
  }
  render() {
    return (
      <div>
           <Suspense fallback={<div>加载中...</div>}>
                 {this._renderLazy()}
           </Suspense>
      </div>
    )
  }
}

使用方法:

image.png

说明

1.源码中,LazyOut传入一个组件,这个可以达到按需引入的目的,默认延迟200ms加载
2.必须传入一个Promise对象,如果组件有错误,会引入并渲染.error的内容。
3.建议将需要懒加载的组件,写成变量的形式,可以懒加载图片,列表,echats等。
4.使用react中的Suspense 和 Lazy

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。