最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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:

創(chuàng)建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() {
  // 加載初始狀態(tài)
  this.load(this.props);
 }

 componentWillReceiveProps(nextProps) {
  if (nextProps.load !== this.props.load) {
   this.load(nextProps);
  }
 }

 load(props) {
  // 重置狀態(tài)
  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統(tǒng)一配置

這里匹配的是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 Mobx狀態(tài)管理工具的使用

    React Mobx狀態(tài)管理工具的使用

    這篇文章主要介紹了React Mobx狀態(tài)管理工具的使用,MobX是一個狀態(tài)管理庫,它會自動收集并追蹤依賴,開發(fā)人員不需要手動訂閱狀態(tài),當狀態(tài)變化之后MobX能夠精準更新受影響的內容,另外它不要求state是可JSON序列化的,也不要求state是immutable
    2023-02-02
  • react實現菜單權限控制的方法

    react實現菜單權限控制的方法

    本篇文章主要介紹了react實現菜單權限控制的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • 列表頁常見hook封裝實例

    列表頁常見hook封裝實例

    這篇文章主要為大家介紹了列表頁常見的hook封裝示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07
  • React使用UI(Ant?Design)框架的詳細過程

    React使用UI(Ant?Design)框架的詳細過程

    Ant?Design主要用于中后臺系統(tǒng)的使用,它提供了豐富的組件和工具,可以幫助開發(fā)人員快速構建出美觀、易用的界面,同時,Ant?Design還提供了詳細的文檔和示例,方便開發(fā)者學習和使用,這篇文章主要介紹了React使用UI(Ant?Design)框架,需要的朋友可以參考下
    2023-12-12
  • React子組件調用父組件方法獲取的數據不是最新值的解決方法

    React子組件調用父組件方法獲取的數據不是最新值的解決方法

    這篇文章主要介紹了React子組件調用父組件方法獲取的數據不是最新值的解決方法,文中通過代碼示例介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下
    2024-09-09
  • 基于React+Redux的SSR實現方法

    基于React+Redux的SSR實現方法

    這篇文章主要介紹了基于React+Redux的SSR實現方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • 詳解在React-Native中持久化redux數據

    詳解在React-Native中持久化redux數據

    這篇文章主要介紹了在React-Native中持久化redux數據,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • 關于react hook useState連續(xù)更新對象的問題

    關于react hook useState連續(xù)更新對象的問題

    這篇文章主要介紹了關于react hook useState連續(xù)更新對象的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • 詳解React服務端渲染從入門到精通

    詳解React服務端渲染從入門到精通

    這篇文章主要介紹了詳解React服務端渲染從入門到精通,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-03-03
  • React中的合成事件是什么原理

    React中的合成事件是什么原理

    React 中的事件,是對原生事件的封裝,叫做合成事件。這篇文章主要通過幾個簡單的示例為大家詳細介紹一下React中的合成事件,感興趣的可以了解一下
    2023-02-02

最新評論

瑞金市| 三穗县| 体育| 浪卡子县| 楚雄市| 胶南市| 萨嘎县| 铜鼓县| 舟曲县| 乌兰浩特市| 井冈山市| 南宫市| 本溪| 兰溪市| 瓦房店市| 宾阳县| 吉隆县| 临泽县| 磴口县| 天津市| 禹州市| 绵竹市| 麻栗坡县| 出国| 镇巴县| 萝北县| 辽阳市| 普兰店市| 于田县| 高尔夫| 钟山县| 福泉市| 苍南县| 定西市| 禹城市| 靖江市| 松原市| 贵阳市| 小金县| 周口市| 辽中县|