Live2D

react-loadable简单实现

什么是react-loadable

npm desc:
A higher order component for loading components with dynamic imports.
一个异步加载component的高阶组件

组件拆分

做路由拆分可以达到一定程度的性能优化,loadable本质上做的事组件拆分

基本用法

import Loadable from 'react-loadable';
 
const LoadableBar = Loadable({
  loader: () => import('./components/Bar'),
  loading() {
    return <div>Loading...</div>
  }
});

 
class MyComponent extends React.Component {
  render() {
    return <LoadableBar/>;
  }
}

简易实现

基本思路,在组件和页面之间加一层代理,通过文件异步加载实现懒加载

import React, { Component } from "react";

const loadable = ({ loader, loading: Loading }) => {
  return class loadableComponent extends Component {
    state = {
      LoadedComponent: null
    };
    componentDidMount() {
      //loader是一个函数 执行import操作
      loader().then(res => {
        console.log(res.default);
        this.setState({ LoadedComponent: res.default });
      });
    }
    render() {
      const { LoadedComponent } = this.state;
      return LoadedComponent ? <loadedComponent /> : <Loading />;
    }
  };
};
export default loadable;

posted @ 2020-03-22 19:00  二胖he鼠标  阅读(865)  评论(0编辑  收藏  举报