欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

React router动态加载组件之适配器模式的应用详解

程序员文章站 2023-11-21 12:19:34
前言 本文讲述怎么实现动态加载组件,并借此阐述适配器模式。 一、普通路由例子 import center from 'page/center'; imp...

前言

本文讲述怎么实现动态加载组件,并借此阐述适配器模式。

一、普通路由例子

import center from 'page/center';
import data from 'page/data';

function app(){
 return (
  <router>
   <switch>
   <route exact path="/" render={() => (<redirect to="/center" />)} />
   <route path="/data" component={data} />
   <route path="/center" component={center} />
   <route render={() => <h1 style={{ textalign: 'center', margintop: '160px', color:'rgba(255, 255, 255, 0.7)' }}>页面不见了</h1>} />
   </switch>
  </router>
 );
}

以上是最常见的react router。在简单的单页应用中,这样写是ok的。因为打包后的单一js文件bundle.js也不过200k左右,gzip之后,对加载性能并没有太大的影响。

 但是,当产品经历多次迭代后,追加的页面导致bundle.js的体积不断变大。这时候,优化就变得很有必要。

二、如何优化

优化使用到的一个重要理念就是——按需加载。

可以结合例子进行理解为:只加载当前页面需要用到的组件。

比如当前访问的是/center页,那么只需要加载center组件即可。不需要加载data组件。

业界目前实现的方案有以下几种:

•react-router的动态路由getcomponent方法(router4已不支持)
•使用react-loadable小工具库
•自定义高阶组件进行按需加载

而这些方案共通的点,就是利用webpack的code splitting功能(webpack1使用require.ensure,webpack2/webpack3使用import),将代码进行分割。

接下来,将介绍如何用自定义高阶组件实现按需加载。

三、自定义高阶组件

3.1 webpack的import方法

webpack将import()看做一个分割点并将其请求的module打包为一个独立的chunk。import()以模块名称作为参数名并且返回一个promise对象。

因为import()返回的是promise对象,所以不能直接给<router/>使用。

3.2 采用适配器模式封装import()

适配器模式(adapter):将一个类的接口转换成客户希望的另外一个接口。adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

当前场景,需要解决的是,使用import()异步加载组件后,如何将加载的组件交给react进行更新。
 方法也很容易,就是利用state。当异步加载好组件后,调用setstate方法,就可以通知到。
 那么,依照这个思路,新建个高阶组件,运用适配器模式,来对import()进行封装。

3.3 实现异步加载方法asynccomponent

import react from 'react';
export const asynccomponent = loadcomponent => (
 class asynccomponent extends react.component {
  constructor(...args){
   super(...args);
   this.state = {
    component: null,
   };
   this.hasloadedcomponent = this.hasloadedcomponent.bind(this);
  }
  componentwillmount() {
   if(this.hasloadedcomponent()){
    return;
   }
   loadcomponent()
    .then(module => module.default ? module.default : module)
    .then(component => {
     this.setstate({
      component
     });
    })
    .catch(error => {
     /*eslint-disable*/
     console.error('cannot load component in <asynccomponent>');
     /*eslint-enable*/
     throw error;
    })
  }
  hasloadedcomponent() {
   return this.state.component !== null;
  }
  render(){
   const {
    component
   } = this.state;
   return (component) ? <component {...this.props} /> : null;
  }
 }
);
// 使用方式
const center = asynccomponent(()=>import(/* webpackchunkname: 'pagecenter' */'page/center'));

如例子所示,新建一个asynccomponent方法,用于接收import()返回的promise对象。

当componentwillmount时(服务端渲染也有该生命周期方法),执行import(),并将异步加载的组件,set入state,触发组件重新渲染。

3.4 释疑

•state.component初始化

this.state = {
 component: null,
};

这里的null,主要用于判断异步组件是否已经加载。

•module.default ? module.default : module

这里是为了兼容具名和default两种export写法。

•return (component) ? <component {...this.props} /> : null;

这里的null,其实可以用<loadingcomponent />代替。作用是:当异步组件还没加载好时,起到占位的作用。
this.props是通过asynccomponent组件透传给异步组件的。

3.5 修改webpack构建

output: {
 path: config.build.assetsroot,
 filename: utils.assetspath('js/[name].[chunkhash].js'),
 chunkfilename: utils.assetspath('js/[id].[chunkhash].js')
}

在输出项中,增加chunkfilename即可。

四、小结

自定义高阶组件的好处,是可以按最少的改动,来优化已有的旧项目。

像上面的例子,只需要改变import组件的方式即可。花最少的代价,就可以得到页面性能的提升。

 其实,react-loadable也是按这种思路去实现的,只不过增加了很多附属的功能点而已。

以上所述是小编给大家介绍的react router动态加载组件之适配器模式的应用,希望对大家有所帮助