[详解九章算法]详解react-router4 异步加载路由两种方法

时间:2021-08-21  来源:C语言  阅读:

方法一:我们要借助bundle-loader来实现按需加载。

首先,新建一个bundle.js文件:

import React, { Component } from "react"

export default 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 (!this.state.mod)
      return false
    return this.props.children(this.state.mod)
  }
}

然后,在入口处使用按需加载:

// ...

// bundle模型用来异步加载组件
import Bundle from "./bundle.js";

// 引入单个页面(包括嵌套的子页面)
// 同步引入
import Index from "./app/index.js";
// 异步引入
import ListContainer from "bundle-loader?lazy&name=app-[name]!./app/list.js";

const List = () => (
  
    {(List) => }
  
)

// ...

  
    
      
        
        
      
    
  

// ...


webpack.config.js文件配置
output: {
  path: path.resolve(__dirname, "./output"),
  filename: "[name].[chunkhash:8].bundle.js",
  chunkFilename: "[name]-[id].[chunkhash:8].bundle.js",
},

方法二:用原生的

Webpack 配置

首先在 webpack.config.js 的 output 内加上 chunkFilename

output: {
  path: path.join(__dirname, "/../dist/assets"),
  filename: "app.js",
  publicPath: defaultSettings.publicPath,
  // 添加 chunkFilename
  chunkFilename: "[name].[chunkhash:5].chunk.js",
},

name 是在代码里为创建的 chunk 指定的名字,如果代码中没指定则 webpack 默认分配 id 作为 name。

chunkhash 是文件的 hash 码,这里只使用前五位。

在路由页面

这里写的是旧的没按需要加载的路由写法

ReactDOM.render(
 (
  
   {/* 主页 */}
   
    {/* 默认 */}
    

    {/* baidu */}
    
     
     
    

    {/* 404 */}
    
    
    {/* 其他重定向到 404 */}
    
   
  
 ), document.getElementById("app")
);

我们需要让路由动态加载组件,需要将 component 换成 getComponent

ReactDOM.render(
 (
  
   {/* 主页 */}
   
    {/* 默认 */}
    

    {/* baidu */}
     { cb(null, require("components/layer/HomePage")) }, "HomePage")}>
     
     
    
    {/* 404 */}
    
    {/* 其他重定向到 404 */}
     replaceState(null, "/404") />
   
  
 ), document.getElementById("app")
);

getComponent

对应于以前的 component 属性,但是这个方法是异步的,也就是当路由匹配时,才会调用这个方法。

这里面有个 require.ensure 方法

require.ensure(dependencies, callback, chunkName)

这是 webpack 提供的方法,这也是按需加载的核心方法。第一个参数是依赖,第二个是回调函数,第三个就是上面提到的 chunkName,用来指定这个 chunk file 的 name。

如果需要返回多个子组件,则使用 getComponents 方法,将多个组件作为一个对象的属性通过 cb 返回出去即可。这个在官方示例也有,但是我们这里并不需要,而且根组件是不能返回多个子组件的,所以使用 getComponent。 

当改写之后,我们需要把这个重定向的路由单独拆出来,也就是 * 这个路由,我们上面已经为他创建了一个 redirect 目录。这里使用到 onEnter 方法,然后在这个方法里改变路由状态,调到另外的路由,实现 redirect :

/redirect/index.js

module.exports = {
 path: "*",
 onEnter: (_, replaceState) => replaceState(null, "/404")
}

The root route must render a single element

跟着官方示例和上面码出来之后,可能页面并没有渲染出来,而是报 The root route must render a single element 这个异常,这是因为 module.exports 和 ES6 里的 export default 有区别。

如果你是使用 es6 的写法,也就是你的组件都是通过 export default 导出的,那么在 getComponent 方法里面需要加入.default。

getComponent(nextState, cb) {
  require.ensure([], (require) => {
   // 在后面加 .default
   cb(null, require("components/layer/ReportPage")).default
  }, "ReportPage")
}

如果你是使用 CommonJS 的写法,也就是通过 module.exports 导出的,那就无须加 .default 了。

[详解九章算法]详解react-router4 异步加载路由两种方法

http://m.bbyears.com/asp/137314.html

推荐访问:详解c语言free 详解24个经典技术指标 地势详解 yo62lo详解 详解redis 详解功放 详解jtag信号 详解tensorflow识别车牌
相关阅读 猜你喜欢
本类排行 本类最新