react学习系列6 react-router 实现异步按需加载模块

简介: 按需加载模块的目的是实现代码分隔,用户打开首页时不用下载全部的代码,打开特定的页面加载特定的代码。提高用户体验。如果使用的是react-router,官网文档给出的 方案 是用webpack的bundle-loader你可能也见过require.ensure。

按需加载模块的目的是实现代码分隔,用户打开首页时不用下载全部的代码,打开特定的页面加载特定的代码。提高用户体验。

如果使用的是react-router,官网文档给出的 方案 是用webpack的bundle-loader

你可能也见过require.ensure。这是webpack的旧式写法,现在已不推荐。

我倾向于使用import(),这也是webpack推荐的。因为更符合规范。 这篇 我有专门的介绍,社区中也有专门的 方案

我也用到项目中,代码如下
其中City和Login页面是按需加载中的,你可以在network中看到进入这俩页面浏览器会先加载类似 1.chunk.js文件。

import React from 'react'
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom'
import Home   from '$pages/Home/'
import List   from '$pages/List/'
// import City   from '$pages/City/'
// import Login  from '$pages/Login/'
import Detail from '$pages/Detail/'
import Search from '$pages/Search/'
import UserCenter  from '$pages/UserCenter/'
import Demo   from '$pages/Demo/'
import NoMatch from './404'

// 异步按需加载component
function asyncComponent(getComponent) {
  return class AsyncComponent extends React.Component {
    static Component = null;
    state = { Component: AsyncComponent.Component };

    componentWillMount() {
      if (!this.state.Component) {
        getComponent().then(({default: Component}) => {
          AsyncComponent.Component = Component
          this.setState({ Component })
        })
      }
    }
    render() {
      const { Component } = this.state
      if (Component) {
        return <Component {...this.props} />
      }
      return null
    }
  }
}

function load(component) {
  return import(`$pages/${component}/`)
}

const Login = asyncComponent(() => load('Login'));
const City = asyncComponent(() => load('City'));

export class RouterMap extends React.Component {
  render() {
    return (
      <Router>
        <div>
          { /*
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/list">List</Link></li>
          </ul>
          <hr/>
          */ }
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/login/:refer?" component={Login} />
            <Route path="/city" component={City} />
            <Route path="/user" component={UserCenter} />
            <Route path="/list" component={List} />
            <Route exact path="/demo" component={Demo} />
            <Route path="/search/:category/:keyword?" component={Search} />
            <Route path="/detail/:id" component={Detail} />
            <Route component={NoMatch}/>
          </Switch>
        </div>
      </Router>
    );
  }
}

如果感觉这篇对你有用的朋友给我的 项目 点个star

相关文章
|
开发框架 前端开发 JavaScript
从零开始学习React Native开发
React Native是一种基于React框架的移动端开发框架,使用它可以快速地构建出高性能、原生的移动应用。本文将从零开始,介绍React Native的基础知识和开发流程,帮助读者快速入门React Native开发,并实现一个简单的ToDo应用程序。
|
人工智能 JSON 前端开发
react17+ts 学习
react17+ts 学习
247 0
|
前端开发 API UED
React 按需加载 Lazy Loading
随着 Web 应用复杂度增加,页面加载速度成为影响用户体验的关键因素。React 提供了按需加载(Lazy Loading)功能,通过 `React.lazy` 和 `Suspense` 实现动态加载组件,减少初始加载时间,提升性能。本文从基础概念入手,探讨常见问题、易错点及解决方案,并通过代码示例详细说明。
626 0
|
资源调度 前端开发 API
React Suspense与Concurrent Mode:异步渲染的未来
React的Suspense与Concurrent Mode是16.8版后引入的功能,旨在改善用户体验与性能。Suspense组件作为异步边界,允许子组件在数据加载完成前显示占位符,结合React.lazy实现懒加载,优化资源调度。Concurrent Mode则通过并发渲染与智能调度提升应用响应性,支持时间分片和优先级调度,确保即使处理复杂任务时UI仍流畅。二者结合使用,能显著提高应用效率与交互体验,尤其适用于数据驱动的应用场景。
314 20
|
前端开发
React按需加载antd步骤以及出现的问题
在使用`babel-plugin-import`插件时,可以在项目的根目录创建`.babelrc`文件或在`package.json`中添加babel配置。这两个文件中不应该存在重复的配置。如果出现"Multiple configuration files found"错误,需要选择其中一个文件进行配置,并删除另一个文件中的babel配置。使用该插件后,可以直接从`antd`引入组件,无需手动引入样式文件。
349 1
|
前端开发 程序员 API
React技术栈-React路由插件之react-router的基本使用
这篇博客介绍了React路由插件react-router的基本使用,包括其概念、API、以及如何通过实战案例在React应用中实现SPA(单页Web应用)的路由管理。
363 9
|
JavaScript 前端开发 API
如何学习React.js?
【5月更文挑战第27天】如何学习React.js?
326 14
|
前端开发 UED 开发者
React.lazy()与Suspense:实现按需加载的动态组件——深入理解代码分割、提升首屏速度和优化用户体验的关键技术
【8月更文挑战第31天】在现代Web应用中,性能优化至关重要,特别是减少首屏加载时间和提升用户交互体验。React.lazy()和Suspense组件提供了一种优雅的解决方案,允许按需加载组件,仅在需要渲染时加载相应代码块,从而加快页面展示速度。Suspense组件在组件加载期间显示备选内容,确保了平滑的加载过渡。
554 0
|
存储 前端开发 JavaScript
处理 React 应用程序中的异步数据加载
【8月更文挑战第31天】
337 0