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

React-router 4 按需加载的实现方式及原理详解

程序员文章站 2022-06-20 10:49:15
react-router 4 介绍了在router4以后,如何去实现按需加载component,在router4以前,我们是使用getcomponent的的方式来实现...

react-router 4

介绍了在router4以后,如何去实现按需加载component,在router4以前,我们是使用getcomponent的的方式来实现按需加载的,router4中,getcomponent方法已经被移除,下面就介绍一下react-router4是入围和来实现按需加载的。

1.router3的按需加载方式

route3中实现按需加载只需要按照下面代码的方式实现就可以了。

const about = (location, cb) => {
  require.ensure([], require => {
    cb(null, require('../component/about').default)
  },'about')
}

//配置route
<route path="helpcenter" getcomponent={about} />

2.router4按需加载方式(three steps)

one step:

创建bundle.js文件,这个文件其实是个通过bundle-loader包装后的组件来使用,下面会具体讲这个东西。

import react from 'react';
import proptypes from 'prop-types';

class bundle extends react.component {
 state = {
  // short for "module" but that's a keyword in js, so "mod"
  mod: null
 }

 componentwillmount() {
  // 加载初始状态
  this.load(this.props);
 }

 componentwillreceiveprops(nextprops) {
  if (nextprops.load !== this.props.load) {
   this.load(nextprops);
  }
 }

 load(props) {
  // 重置状态
  this.setstate({
   mod: null
  });
  // 传入组件的组件
  props.load((mod) => {
   this.setstate({
    // handle both es imports and cjs
    mod: mod.default ? mod.default : mod
   });
  });
 }

 render() {
  // if state mode not undefined,the container will render children
  return this.state.mod ? this.props.children(this.state.mod) : null;
 }
}

bundle.proptypes = {
 load: proptypes.func,
 children: proptypes.func
};

export default bundle;

second step:

import acontainer from 'bundle-loader?lazy!./containers/a'

const a = (props) => (
 <bundle load={acontainer}>
   //这里只是给this.props.child传一个方法,最后在bundle的render里面调用
  {(container) => <container {...props}/>}
 </bundle>
)

third step:

 render() {
  return (
   <div>
    <h1>welcome!</h1>
    <route path="/about" component={about}/>
    <route path="/dashboard" component={a}/>
   </div>
  )
 }

3.router4按需加载方方式解析

(1).首先解释一下按需加载,通俗的将就是我当前的location在home,那么我只应该加载home的东西,而不应该去加载about等等其他的。

(2).bundle.js这个文件的作用

先看这段代码:

module.exports = function (cb) {
  __webpack_require__.e/* require.ensure */(2).then((function (require) {
    cb(__webpack_require__(305));
  }).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
};

这里是我们通过import loaddashboard from 'bundle-loader?lazy!./containers/a'这种方式引入的container控件。我们使用了bundle-loader将a的源码转化成了上面的代码,具体实现大家可以看bundle-loader源码,代码很少。

上面说到bundle.js其实就使用来处理这个文件的,这个文件需要一个callback的参数,在bundle的load方法中,我们会设置这个callback,当路由要调到a container这里的时候,就回去加载a container,然后调用这个callback,这个callback会调用setstate方法,将我们之前传入的load设置给mod,然后渲染出来。

4.webpack进行bundle-loader统一配置

这里匹配的是src/routers/下面的containers文件夹下面所有的js文件,包括二级目录。

 {
   // 匹配routers下面所有文件
   // ([^/]+)\/?([^/]*) 匹配xxx/xxx 或者 xxx
   test: /containers\/([^/]+)\/?([^/]*)\.jsx?$/,
   include: path.resolve(__dirname, 'src/routers/'),
   // loader: 'bundle-loader?lazy'
   loaders: ['bundle-loader?lazy', 'babel-loader']
  }

5.部分源码

1.bundle-loader的源码

var loaderutils = require("loader-utils");

module.exports = function() {};
module.exports.pitch = function(remainingrequest) {
  this.cacheable && this.cacheable();
  var query = loaderutils.getoptions(this) || {};
  if(query.name) {
    var options = {
      context: query.context || this.options.context,
      regexp: query.regexp
    };
    var chunkname = loaderutils.interpolatename(this, query.name, options);
    var chunknameparam = ", " + json.stringify(chunkname);
  } else {
    var chunknameparam = '';
  }
  var result;
  if(query.lazy) {
    result = [
      "module.exports = function(cb) {\n",
      "  require.ensure([], function(require) {\n",
      "    cb(require(", loaderutils.stringifyrequest(this, "!!" + remainingrequest), "));\n",
      "  }" + chunknameparam + ");\n",
      "}"];
  } else {
    result = [
      "var cbs = [], \n",
      "  data;\n",
      "module.exports = function(cb) {\n",
      "  if(cbs) cbs.push(cb);\n",
      "  else cb(data);\n",
      "}\n",
      "require.ensure([], function(require) {\n",
      "  data = require(", loaderutils.stringifyrequest(this, "!!" + remainingrequest), ");\n",
      "  var callbacks = cbs;\n",
      "  cbs = null;\n",
      "  for(var i = 0, l = callbacks.length; i < l; i++) {\n",
      "    callbacks[i](data);\n",
      "  }\n",
      "}" + chunknameparam + ");"];
  }
  return result.join("");
}

/*
output format:

  var cbs = [],
    data;
  module.exports = function(cb) {
    if(cbs) cbs.push(cb);
    else cb(data);
  }
  require.ensure([], function(require) {
    data = require("xxx");
    var callbacks = cbs;
    cbs = null;
    for(var i = 0, l = callbacks.length; i < l; i++) {
      callbacks[i](data);
    }
  });

*/

2.a的源码

import react from 'react';
import proptypes from 'prop-types';
import * as reactredux from 'react-redux';
import basecontainer from '../../../containers/reactbasecontainer';

class a extends basecontainer {
 constructor(props) {
  super(props);
  this.rendercustom = function rendercustom() {
   return (
    <div >
     hello world in a
    </div>
   );
  };
 }
 render() {
  // 返回父级view
  return super.render();
 }
}

a.proptypes = {
 dispatch: proptypes.func,
};

function mapstatetoprops(state) {
 return { state };
}

export default reactredux.connect(mapstatetoprops)(a);

3.route.js的源码

import react from 'react';
import { browserrouter, switch, link } from 'react-router-dom';
import { route } from 'react-router';
import postcontainer from '../containers/postscontainer';
// 设置trunk文件的名字 the basename of the resource
import acontainer from './containers/a';
import bcontainer from './containers/b';
import ccontainer from './containers/c';
import bundle from '../utils/bundle';

const a = () => (
 <bundle load={acontainer}>
  {component => <component />}
 </bundle>
)

const app = () =>
 <div>
  {/* path = "/about" */}
  {/* "/about/" 可以,但"/about/1"就不可以了 exact 配置之后,需要路径绝对匹配,多个斜杠没有关系,这里直接在浏览器里面设置还有问题*/}
  {/* path = "/about/" */}
  {/* "/about/1" 可以,但"/about"就不可以了 用了strict,path要大于等于的关系,少一个斜杠都不行 */}
  {/* exact 和 strick 都用了就必须一模一样,连斜杠都一样 */}
  <link to="/about/"> link to about</link>
  <route path="/" component={postcontainer} />
  <route path="/about/" component={a} />
  {/* <route path="/home" component={b} />
  <route component={c} /> */}
 </div>
;
export default function () {
 // 用来判断本地浏览器是否支持刷新
 const supportshistory = 'pushstate' in window.history;
 return (
  <browserrouter forcerefresh={!supportshistory} keylength={12}>
   <div>
    {app()}
   </div>
  </browserrouter>

 );
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。