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

69 阅读1分钟

课程简介

  • 了解路由的演进历史&原因
  • 了解React-Router的原理
  • 复杂前端应用里结合路由的最佳实践

路由介绍

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

image.png

image.png

image.png

React-Router

React Router 是一个基于 React 之上的强大路由库,它可以让你向应用中快速地添加视图和数据流,同时保持页面与 URL 间的同步。

不使用 React Router

import React from 'react'
import { render } from 'react-dom'

const About = React.createClass({/*...*/})
const Inbox = React.createClass({/*...*/})
const Home = React.createClass({/*...*/})

const App = React.createClass({
  getInitialState() {
    return {
      route: window.location.hash.substr(1)
    }
  },

  componentDidMount() {
    window.addEventListener('hashchange', () => {
      this.setState({
        route: window.location.hash.substr(1)
      })
    })
  },

  render() {
    let Child
    switch (this.state.route) {
      case '/about': Child = About; break;
      case '/inbox': Child = Inbox; break;
      default:      Child = Home;
    }

    return (
      <div>
        <h1>App</h1>
        <ul>
          <li><a href="#/about">About</a></li>
          <li><a href="#/inbox">Inbox</a></li>
        </ul>
        <Child/>
      </div>
    )
  }
})

React.render(<App />, document.body)

使用 React Router

import React from 'react'
import { render } from 'react-dom'

import { Router, Route, Link } from 'react-router'

const App = React.createClass({
  render() {
    return (
      <div>
        <h1>App</h1>
        <ul>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/inbox">Inbox</Link></li>
        </ul>
        {this.props.children}
      </div>
    )
  }
})

React.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
      <Route path="inbox" component={Inbox} />
    </Route>
  </Router>
), document.body)

image.png

image.png

image.png

路由实践

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

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

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

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

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

海量数据接口请求