当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解react-router4 异步加载路由两种方法

详解react-router4 异步加载路由两种方法

2017年12月12日  | 移动技术网IT编程  | 我要评论
方法一:我们要借助bundle-loader来实现按需加载。 首先,新建一个bundle.js文件: import react, { component }

方法一:我们要借助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 = () => (
  <bundle load={listcontainer}>
    {(list) => <list />}
  </bundle>
)

// ...

  <hashrouter>
    <router basename="/">
      <div>
        <route exact path="/" component={index} />
        <route path="/list" component={list} />
      </div>
    </router>
  </hashrouter>

// ...


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(
 (
  <router history={browserhistory}>
   {/* 主页 */}
   <route path="/" component={app}>
    {/* 默认 */}
    <indexroute component={homepage} />

    {/* baidu */}
    <route path="/baidu" component={baidupage}>
     <route path="result" component={baiduresultpage} />
     <route path="frequency" component={baidufrequencypage} />
    </route>

    {/* 404 */}
    <route path='/404' component={notfoundpage} />
    
    {/* 其他重定向到 404 */}
    <redirect from='*' to='/404' />
   </route>
  </router>
 ), document.getelementbyid('app')
);

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

reactdom.render(
 (
  <router history={browserhistory}>
   {/* 主页 */}
   <route path="/" component={app}>
    {/* 默认 */}
    <indexroute component={homepage} />

    {/* baidu */}
    <route path="/baidu"
          getcomponent(nextstate, cb) 
          { require.ensure([], (require) => { cb(null, require('components/layer/homepage')) }, 'homepage')}>
     <route path="result"   getcomponent... />
     <route path="frequency" getcomponent... />
    </route>
    {/* 404 */}
    <route path='/404' getcomponent... />
    {/* 其他重定向到 404 */}
    <redirect path='*' onenter: (_, replacestate) => replacestate(null, "/404") />
   </route>
  </router>
 ), 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 了。

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网