前端路由解析(三) —— React-Router源码解析

简介: 前端路由解析(三) —— React-Router源码解析

640.jpg



写在前面

现在的前端应用很多都是单页应用。路由对于单页应用来说,是一个重要的组成部分。本系列文章将讲解前端路由的实现原理。这是系列文章的第三篇:React-Router源码解析。


前端路由解析(一) ——  hash路由

前端路由解析(二) ——  history路由


本文不会再介绍路由的基本原理,而是会结合React-Router的源码,探索一下路由和React是如何结合的。


示例代码


本文所用的React-Router的版本为:5.1.2,react版本为:16.12.0

我们用官方最简单的代码示例来分析一下React-Router的源码。


import {    BrowserRouter as Router,    Switch,    Route,    Link} from "react-router-dom";
export default function App() {    return (        <Router>            <div>                <nav>                    <ul>                        <li>                            <Link to="/">Home</Link>                        </li>                        <li>                            <Link to="/about">About</Link>                        </li>                        <li>                            <Link to="/users">Users</Link>                        </li>                    </ul>                </nav>
                {/* A <Switch> looks through its children <Route>s and            renders the first one that matches the current URL. */}                <Switch>                    <Route path="/about">                        <About />                    </Route>                    <Route path="/users">                        <Users />                    </Route>                    <Route path="/">                        <Home />                    </Route>                </Switch>            </div>        </Router>    );}
function Home() {    return <h2>Home</h2>;}
function About() {    return <h2>About</h2>;}
function Users() {    return <h2>Users</h2>;}


初次渲染


下面依次对 BrowserRouter、Switch、Route、Link进行解析。

BrowserRouter


import { Router } from 'react-router';
..._this.history = createBrowserHistory(_this.props);
...
_proto.render = function render() {  return React.createElement(Router, {    history: this.history,    children: this.props.children  });};


其中,Router来自react-router这个库,是react路由的核心组件,其内部维护了一个state。当页面的路由发生变化时,会更新state的location值,从而触发react的re-render。


/*interface Location<S = LocationState> {    pathname: Pathname;    search: Search;    state: S;    hash: Hash;    key?: LocationKey;} */
_this.state = {     location: props.history.location }


props.history,是createBrowserHistory这个函数生成的,createBrowserHistory是来自history这个package,返回了一个对象:


// 请记住这个history对象var history = {    length: globalHistory.length,    action: 'POP',    location: initialLocation,    createHref: createHref,    push: push,    replace: replace,    go: go,    goBack: goBack,    goForward: goForward,    block: block,    listen: listen};return history;


Router组件渲染时,会将上述的方法、对象,传递给需要的childern组件。传递是通过 context 完成的。Router会在childern外包一层 Router.Provider,来提供history对象等信息。


// 这里的 context.Provider 是一个组件。使用的是 mini-create-react-context 这个 package。参考React.createContext
_proto.render = function render() {    return React.createElement(context.Provider, {      children: this.props.children || null,      value: {        history: this.props.history,        location: this.state.location,        match: Router.computeRootMatch(this.state.location.pathname),        staticContext: this.props.staticContext      }    });};


Switch


...
_proto.render = function render() {    var _this = this;
    return React.createElement(context.Consumer, null, function (context) {      !context ? process.env.NODE_ENV !== "production" ? invariant(false, "You should not use <Switch> outside a <Router>") : invariant(false) : void 0;      var location = _this.props.location || context.location;      var element, match; // We use React.Children.forEach instead of React.Children.toArray().find()       React.Children.forEach(_this.props.children, function (child) {        if (match == null && React.isValidElement(child)) {          element = child;          var path = child.props.path || child.props.from;          match = path ? matchPath(location.pathname, _extends({}, child.props, {            path: path          })) : context.match;        }      });      return match ? React.cloneElement(element, {        location: location,        computedMatch: match      }) : null;    });  };


Switch 会找到第一个匹配当前路由的Route,来进行渲染。Switch会在childern外面包一层Router.Comsumer。这个是为了通过context,拿到外层Router组件传递的history对象相关信息传递给Route组件。


Route


Route组件的逻辑也很好理解,首先是通过Router.Consumer拿到history对象等相关信息,经过一些处理后,在children外面包一层Router.Provider, 然后渲染children。之所以要包一层,我理解是为了供children中的Link组件等消费。来看代码:


...
proto.render = function render() {    var _this = this;
    return React.createElement(context.Consumer, null, function (context$1) {      !context$1 ? process.env.NODE_ENV !== "production" ? invariant(false, "You should not use <Route> outside a <Router>") : invariant(false) : void 0;      var location = _this.props.location || context$1.location;      var match = _this.props.computedMatch ? _this.props.computedMatch // <Switch> already computed the match for us      : _this.props.path ? matchPath(location.pathname, _this.props) : context$1.match;
      var props = _extends({}, context$1, {        location: location,        match: match      });
      var _this$props = _this.props,          children = _this$props.children,          component = _this$props.component,          render = _this$props.render; // Preact uses an empty array as children by      // default, so use null if that's the case.
      if (Array.isArray(children) && children.length === 0) {        children = null;      }
      return React.createElement(context.Provider, {        value: props      }, props.match ? children ? typeof children === "function" ? process.env.NODE_ENV !== "production" ? evalChildrenDev(children, props, _this.props.path) : children(props) : children : component ? React.createElement(component, props) : render ? render(props) : null : typeof children === "function" ? process.env.NODE_ENV !== "production" ? evalChildrenDev(children, props, _this.props.path) : children(props) : null);    });    ...


Link

Link组件最终会render一个包裹着Router.Consumer的LinkAnchor组件。Router.Consumer是为了获取外层Router组件的history对象等信息,LinkAnchor绑定了特殊的点击跳转逻辑的<a/>标签。这里先不展开了。


小结


初次渲染后,示例代码会形成下面这样的组件树:

640.png


分析了这么久,可以发现 :react-router-dom 主要的逻辑是处理history对象在整个react应用中的传递以及children的渲染等。history对象的传递是通过context完成的。history对象是由history 这个package中的createBrowserHistory函数生成的。而真正处理路由的核心逻辑, 是在 history 这个package中。

下面,我们来看看点击Link后,会发生什么?


点击Link



点击link后,最终会调用到history对象中的方法来进行路由的切换。


function navigate() {   var location = resolveToLocation(to, context.location);   // 这里的history,就是 createBrowserHistory 方法生成,并且在react组件树中传递的对象   var method = replace ? history.replace : history.push;   method(location);}

下面,进入history中的逻辑:


var href = createHref(location);var key = location.key,    state = location.state;
if (canUseHistory) {  // 调用window.history.pushState  globalHistory.pushState({    key: key,    state: state  }, null, href);
  if (forceRefresh) {    window.location.href = href;  } else {    var prevIndex = allKeys.indexOf(history.location.key);    var nextKeys = allKeys.slice(0, prevIndex + 1);    nextKeys.push(location.key);    allKeys = nextKeys;    // 更新状态。注意,这里的setState可不是react中的setState    setState({      action: action,      location: location    });  }}

我们来看下history中的setState干了什么:


function setState(nextState) {  // 更新history对象  _extends(history, nextState);
  history.length = globalHistory.length;  // 通知订阅者,history已更新。控制react组件重新渲染的关键就在这里  transitionManager.notifyListeners(history.location, history.action);}

其实,在Router组件初始化的时候,就监听了history的更新,下面是Router组件的代码:


...  // 这里的history.listen是history对象提供的方法,用于监听页面history的更新。  _this.unlisten = props.history.listen(function (location) {    if (_this._isMounted) {      _this.setState({        location: location      });    } else {      _this._pendingLocation = location;    }  });
...

可以看到,Router组件监听了history的更新。当页面的history更新时,会调用Router组件的setState,从而完成页面的re-render。


总结


hashHistory的逻辑与BrowserHistory的逻辑类似,本文就不再继续展开了,

到这里,可以简单总结一下,整个react-router的实现思路是:

使用一个第三方的、框架无关的history对象来控制页面的路由变化逻辑。在react侧,使用context来传递history对象,保证路由组件中可以访问到history对象、方便控制路由,并且将history对象与业务组件隔离。使用发布订阅模式,解耦了页面路由的更新与react的更新。

在我们自己的业务组件中,无法直接访问到history对象。如果想直接访问到history对象,可以使用withRouter这个HOC。


写在后面


前端路由系列文章算是告一段落了。本系列文章从最基本的路由原理讲起,到框架的路由实现结束,还算符合预期。不过路由中还涉及到不少的知识点 以及一些高级的功能(比如 keep-alive),值得继续研究

相关文章
|
4月前
|
JavaScript 前端开发 Java
制造业ERP源码,工厂ERP管理系统,前端框架:Vue,后端框架:SpringBoot
这是一套基于SpringBoot+Vue技术栈开发的ERP企业管理系统,采用Java语言与vscode工具。系统涵盖采购/销售、出入库、生产、品质管理等功能,整合客户与供应商数据,支持在线协同和业务全流程管控。同时提供主数据管理、权限控制、工作流审批、报表自定义及打印、在线报表开发和自定义表单功能,助力企业实现高效自动化管理,并通过UniAPP实现移动端支持,满足多场景应用需求。
365 1
|
5月前
|
移动开发 前端开发 JavaScript
Vue与React两大前端框架的主要差异点
以上就是Vue和React的主要差异点,希望对你有所帮助。在选择使用哪一个框架时,需要根据项目的具体需求和团队的技术栈来决定。
319 83
|
5月前
|
前端开发 Java 物联网
智慧班牌源码,采用Java + Spring Boot后端框架,搭配Vue2前端技术,支持SaaS云部署
智慧班牌系统是一款基于信息化与物联网技术的校园管理工具,集成电子屏显示、人脸识别及数据交互功能,实现班级信息展示、智能考勤与家校互通。系统采用Java + Spring Boot后端框架,搭配Vue2前端技术,支持SaaS云部署与私有化定制。核心功能涵盖信息发布、考勤管理、教务处理及数据分析,助力校园文化建设与教学优化。其综合性和可扩展性有效打破数据孤岛,提升交互体验并降低管理成本,适用于日常教学、考试管理和应急场景,为智慧校园建设提供全面解决方案。
366 70
|
4月前
|
存储 前端开发 JavaScript
|
6月前
|
前端开发 算法 NoSQL
前端uin后端php社交软件源码,快速构建属于你的交友平台
这是一款功能全面的社交软件解决方案,覆盖多种场景需求。支持即时通讯(一对一聊天、群聊、文件传输、语音/视频通话)、内容动态(发布、点赞、评论)以及红包模块(接入支付宝、微信等第三方支付)。系统采用前后端分离架构,前端基于 UniApp,后端使用 PHP 框架(如 Laravel/Symfony),配合 MySQL/Redis 和自建 Socket 服务实现高效实时通信。提供用户认证(JWT 集成)、智能匹配算法等功能,助力快速上线,显著节约开发成本。
128 0
前端uin后端php社交软件源码,快速构建属于你的交友平台
|
5月前
|
监控 前端开发 小程序
陪练,代练,护航,代打小程序源码/前端UNIAPP-VUE2.0开发 后端Thinkphp6管理/具备家政服务的综合型平台
这款APP通过技术创新,将代练、家政、娱乐社交等场景融合,打造“全能型生活服务生态圈”。以代练为切入点,提供模块化代码支持快速搭建平台,结合智能匹配与技能审核机制,拓展家政服务和商业管理功能。技术架构具备高安全性和扩展性,支持多业务复用,如押金冻结、录屏监控等功能跨领域应用。商业模式多元,包括交易抽成、增值服务及广告联名,同时设计跨领域积分体系提升用户粘性,实现生态共生与B端赋能。
382 12
|
6月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
534 29
|
8月前
|
机器学习/深度学习 人工智能 自然语言处理
DeepSeek Artifacts:在线实时预览的前端 AI 编程工具,基于DeepSeek V3快速生成React App
DeepSeek Artifacts是Hugging Face推出的免费AI编程工具,基于DeepSeek V3,支持快速生成React和Tailwind CSS代码,适合快速原型开发和前端组件构建。
2056 39
DeepSeek Artifacts:在线实时预览的前端 AI 编程工具,基于DeepSeek V3快速生成React App
|
7月前
|
前端开发 Java Shell
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
395 20
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
|
6月前
|
Web App开发 移动开发 前端开发
React音频播放器样式自定义全解析:从入门到避坑指南
在React中使用HTML5原生&lt;audio&gt;标签时,开发者常面临视觉一致性缺失、样式定制局限和交互体验割裂等问题。通过隐藏原生控件并构建自定义UI层,可以实现完全可控的播放器视觉风格,避免状态不同步等典型问题。结合事件监听、进度条拖拽、浏览器兼容性处理及性能优化技巧,可构建高性能、可维护的音频组件,满足跨平台需求。建议优先使用成熟音频库(如react-player),仅在深度定制需求时采用原生方案。
206 12

推荐镜像

更多
  • DNS