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

 更新时间:2017年05月25日 10:30:34   作者:zhiwei  
本篇文章主要介绍了React-router 4 按需加载的实现方式及原理详解,非常具有实用价值,需要的朋友可以参考下

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>

 );
}

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

相关文章

  • React详细讲解JSX和组件的使用

    React详细讲解JSX和组件的使用

    jsx就是javsscript与xml结合的一种格式,是js语法的一种扩展,只要把html代码写在js中就是jsx。react中定义组件有3种写法:函数的方式、es5的写法、es6(类)的写法
    2022-08-08
  • React+Antd+Redux实现待办事件的方法

    React+Antd+Redux实现待办事件的方法

    这篇文章主要介绍了React+Antd+Redux实现待办事件的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • Unity RectTransform详解

    Unity RectTransform详解

    unity中的ui元素是有严格的父子关系的,子物体的位置是根据父物体的变化而变化的,而子物体和父物体联系的桥梁就是Anchor,本文重点介绍Unity RectTransform的相关知识,感兴趣的朋友一起看看吧
    2024-01-01
  • react实现每隔60s刷新一次接口的示例代码

    react实现每隔60s刷新一次接口的示例代码

    本文主要介绍了react实现每隔60s刷新一次接口的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • react中使用forEach或map两种方式遍历数组

    react中使用forEach或map两种方式遍历数组

    这篇文章主要介绍了react中使用forEach或map两种方式遍历数组,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • reactjs学习解决unknown at rule @tailwind css问题

    reactjs学习解决unknown at rule @tailwind css

    这篇文章主要介绍了reactjs学习解决unknown at rule @tailwind css问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • 在Create React App中启用Sass和Less的方法示例

    在Create React App中启用Sass和Less的方法示例

    这篇文章主要介绍了在Create React App中启用Sass和Less的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • React组件的生命周期详细描述

    React组件的生命周期详细描述

    本篇文章主要介绍了React组件生命周期,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-10-10
  • React中useLayoutEffect钩子使用场景详解

    React中useLayoutEffect钩子使用场景详解

    这篇文章主要为大家介绍了React中useLayoutEffect钩子使用场景详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • React RenderProps模式超详细讲解

    React RenderProps模式超详细讲解

    render props是指一种在 React 组件之间使用一个值为函数的 prop 共享代码的技术。简单来说,给一个组件传入一个prop,这个props是一个函数,函数的作用是用来告诉这个组件需要渲染什么内容,那么这个prop就成为render prop
    2022-11-11

最新评论