经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JSJS库框架 » JavaScript » 查看文章
深入理解react-router 路由的实现原理
来源:jb51  时间:2018/9/27 16:26:37  对本文有异议

React Router 是一个基于 React 之上的强大路由库,它可以让你向应用中快速地添加视图和数据流,同时保持页面与 URL 间的同步。本文从两个方便来解析 react-router 实现原理。一:介绍 react-router 的依赖库history;二:使用 history 库,实现一个简单的 react-router 路由。

history 介绍

history 是一个 JavaScript 库,可让您在 JavaScript 运行的任何地方轻松管理会话历史记录。history 抽象出各种环境中的差异,并提供最小的 API ,使您可以管理历史堆栈,导航,确认导航以及在会话之间保持状态。

history 有三种实现方式:

1、BrowserHistory:用于支持 HTML5 历史记录 API 的现代 Web 浏览器(请参阅跨浏览器兼容性)
2、HashHistory:用于旧版Web浏览器
3、MemoryHistory:用作参考实现,也可用于非 DOM 环境,如 React Native 或测试

三种实现方法,都是创建了一个 history 对象,这里主要讲下前面两种:

  1. const history = {
  2. length: globalHistory.length,
  3. action: "POP",
  4. location: initialLocation,
  5. createHref,
  6. push, // 改变location
  7. replace,
  8. go,
  9. goBack,
  10. goForward,
  11. block,
  12. listen //监听路由变化
  13. };

1.页面跳转实现

BrowserHistory:pushState、replaceState;

HashHistory:location.hash、location.replace

  1. function push(){
  2. createKey(); // 创建location的key,用于唯一标示该location,是随机生成的
  3. if(BrowserHistory){
  4. globalHistory.pushState({ key, state }, null, href);
  5. }else if(HashHistory){
  6. window.location.hash = path;
  7. }
  8. //上报listener 更新state ...
  9. }
  10. function replace(){
  11. createKey(); // 创建location的key,用于唯一标示该location,是随机生成的
  12. if(BrowserHistory){
  13. globalHistory.replaceState({ key, state }, null, href);
  14. }else if(HashHistory){
  15. window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + "#" path);
  16. }
  17. //上报listener 更新state ...
  18. }

2.浏览器回退

BrowserHistory:popstate;

HashHistory:hashchang;

  1. if(BrowserHistory){
  2. window.addEventListener("popstate", routerChange);
  3. }else if(HashHistory){
  4. window.addEventListener("hashchange", routerChange);
  5. }
  6. function routerChange(){
  7. const location = getDOMLocation(); //获取location
  8. //路由切换
  9. transitionManager.confirmTransitionTo(location,callback=()=>{
  10. //上报listener
  11. transitionManager.notifyListeners();
  12. });
  13. }

通过 history 实现简单 react-router

  1. import { Component } from 'react';
  2. import createHistory from 'history/createHashHistory';
  3. const history = createHistory(); //创建 history 对象
  4. /**
  5. * 配置路由表
  6. * @type {{"/": string}}
  7. */
  8. const router = {
  9. '/': 'page/home/index',
  10. '/my': 'page/my/index'
  11. }
  12. export default class Router extends Component {
  13. state = { page: null }
  14.  
  15. async route(location) {
  16. let pathname = location.pathname;
  17. let pagePath = router[pathname];
  18. // 加 ./的原因 https://webpack.docschina.org/api/module-methods#import-
  19. const Page = await import(`./${pagePath}`); //获取路由对应的ui
  20. //设置ui
  21. this.setState({
  22. Page: Page.default
  23. });
  24. }
  25.  
  26. initListener(){
  27. //监听路由切换
  28. history.listen((location, action) => {
  29. //切换路由后,更新ui
  30. this.route(location);
  31. });
  32. }
  33.  
  34. componentDidMount() {
  35. this.route(history.location);
  36. this.initListener();
  37. }
  38.  
  39. render() {
  40. const { Page } = this.state;
  41. return Page && <Page {...this.props} />;
  42. }
  43. }
  44.  

目前react-router在项目中已有大量实践,其优点可以总结如下:

风格: 与React融为一体,专为react量身打造,编码风格与react保持一致,例如路由的配置可以通过component来实现

简单: 不需要手工维护路由state,使代码变得简单

强大: 强大的路由管理机制,体现在如下方面

  • 路由配置: 可以通过组件、配置对象来进行路由的配置
  • 路由切换: 可以通过<Link> Redirect进行路由的切换
  • 路由加载: 可以同步记载,也可以异步加载,这样就可以实现按需加载

使用方式: 不仅可以在浏览器端的使用,而且可以在服务器端的使用

当然react-router的缺点就是API不太稳定,在升级版本的时候需要进行代码变动。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号