React 路由与项目实战| 青训营笔记

234 阅读2分钟

1. 那些年我们一起写过的路由

路由是什么

路由(Router)是一种负责寻径的网络设备,它在互连网络中从多条路径中寻找通讯量最少的一条网络路径提供给用户通信。路由用于连接多个逻辑上分开的网络。对用户提供最佳的通信路径。

浏览器输入一段 URL 后会发生什么

1.drawio.png

在前端发展的过程中,扮演此处的 Provider 角色的节点也在不断变化。

2.drawio.png

2. React-router

import React from "react";
import ReactDOM from "react-dom";
import { BrowserROuter as Router, Route } from "react-router-dom";
​
ReactDOM.render (
    <Router>
        <div>
            <Route exact path="/">
                <Home />
            </Route>
            <Route path="/news">
                <NewsFeed />
            </Route>
        </div>
    </Router>,
    node
);
PackageVersionDocsDescription
react-routernpm v6.5.0API Docs site API Docs markdownThe core of React Router
react-router-domnpm v6.5.0API Docs site API Docs markdownDOM bindings for React Router
react-router-nativenpm v6.5.0API Docs site API Docs markdownReact Native bindings for React Router
react-router-confignpm v5.1.1API Docs readmeStatic route config hepers

4.drawio.png

5.drawio.png

6.png

History 接口允许操作浏览器的曾经在标签页或者框架里访问的会话历史记录。

7.drawio.png

  • Memory history stores the current location in memory. It is designed for use in stateful non-browser environments like tests and React Native.
  • Browser history stores the location in regular URLs. This is the standard for most web apps, but it requires some configuration on the server to ensure you serve the same app at multiple URLs.
  • Hash history stores the location in window.location.hash. This makes it ideal for situations where you don't want to send the location to the server for some reason,either because you do cannot configure it or the URL space is reserved for something else.

8.png

9.png

10.drawio.png

3. 路由实践

11.drawio.png

  • 打开任意页面,白屏时间超长

    js bundle 资源超大,静态资源超多。

  • 一个旁支页面的变更升级,导致主页直接崩溃

    一个 SPA 应用承载 200+ 页面,巨石应用,变更升级风险极大。

  • 页面加载后,数据内容空白时间超长

    海量数据接口请求。

  • 应用开发,构建,交付粒度需要瘦身 & 切割

  • 解决数据加载,前端数据处理的耗时

lmport+Lazy +Suspense

  • import()+babel-plugin-syntax-dynamic-import,识别分割模块
  • Lazy 进行异步加载
  • suspense 包裹动态组件, cover 异步加载前的 Ul