react路由按需加载

在单页应用中,路由按需加载是十分有必要的,如果一次性加载全部js的话,随着应用的功能丰富,js文件也必将增大,那么第一次下载的时候必将变慢,影响用户体验。本文分享react-routerV4版本的按需加载。

异步加载包装组件

首先我们需要一个异步加载包装组件

import { Component } from 'react'

export default class Bundle extends Component {
  constructor(props) {
      super(props);
      this.state = {
          mod: null
      };
  }

  componentWillMount() {
      this.load(this.props)
  }

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

  load(props) {
      this.setState({
          mod: null
      });
      //注意这里,使用Promise对象; mod.default导出默认
      props.load().then((mod) => {
          this.setState({
              mod: mod.default ? mod.default : mod
          });
      });
  }

  render() {
      return this.state.mod ? this.props.children(this.state.mod) : null;
  }
}

路由配置

import React from 'react'
import {
  Route
} from 'react-router-dom'
import App from '../App'
import Bundle from '../components/Bundle'

const Find = (props) => (
  <Bundle load={() => import('../components/Find')}>
      {(Find) => <Find {...props}/>}
  </Bundle>
);
const Home = (props) => (
  <Bundle load={() => import('../containers/Home')}>
      {(Home) => <Home {...props}/>}
  </Bundle>
);

const routes = (
  <Route>
    <div>
    <Route path="/" component={App} />
    <Route path="/home" component={Home} />
    <Route path="/find" component={Find} />
    </div>
  </Route>
)

export default routes;

按照如上配置,webpack打包时就可以实现路由的按需加载了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值