react-router@4.0 使用方法和源码分析

react-router@4.0 使用方法和源码分析

react-router-dom@4.3.0 || react-router@4.4.1

react-router 使用方法

配置 router.js

import React, { Component } from 'react';
import {  Switch, Route } from 'react-router-dom';

const router = [{
    path: '/',
    exact: true,
    component:importPath({
      loader: () => import(/* webpackChunkName:"home" */ "pages/home/index.js"),
    }),
  },]
const Routers = () => (
  <main>
    <Switch>
      {
        router.map(({component,path,exact},index)=>{
          return <Route exact={exact}  path={path} component={component} key={path} />
        })
      }
    </Switch>
  </main>
);

export default Routers;
复制代码

入口 index.js

import {HashRouter} from 'react-router-dom';
import React from 'react';
import ReactDOM from 'react-dom';
import Routers from './router';

ReactDOM.render (
      <HashRouter>
        <Routers />
      </HashRouter>,
  document.getElementById ('App')
);
复制代码

home.js

import { withRouter } from "react-router-dom";

@withRouter
class Home extends React.Component<PropsType, stateType> {
  constructor(props: PropsType) {
    super(props);
    this.state = {};
  }
  goPath=()=>{
      this.props.history.push('/home')
  }
  render() {
    return (
      <div onClick={this.goPath}>home</div>
    );
  }
export default Home;

复制代码

react-router 源码解析

下面代码中会移除部分的类型检查和提醒代码,突出重点代码

第一步 Switch react-router

function _possibleConstructorReturn(self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  if(call&&(typeof call === "object" || typeof call === "function") ){
    return call
  }else {
    return self
  }
}
var Switch = function (_React$Component) {
  function Switch() {
    //使用传递进来的组件覆盖本身
    return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));  
  }
  Switch.prototype.render = function render() {
    var route = this.context.router.route;
    var children = this.props.children;
    var location = this.props.location || route.location;
    var match = void 0,child = void 0;
    
    //检查element是否是react组件,初始match为null,
    React.Children.forEach(children, function (element) {
     //如果match符合,forEach不会进入该if
      if (match == null && React.isValidElement(element)) { 
        var _element$props = element.props,
            pathProp = _element$props.path,
            exact = _element$props.exact,
            strict = _element$props.strict,
            sensitive = _element$props.sensitive,
            from = _element$props.from;
        var path = pathProp || from;
        child = element; 
        //检查当前配置是否符合,
        match = matchPath(location.pathname, { path: path, exact: exact, strict: strict, sensitive: sensitive }, route.match); 
      }
    });
    //如果有匹配元素,则返回克隆child
    return match ? React.cloneElement(child, { location: location, computedMatch: match }) : null;
  };

  return Switch;
}(React.Component);

复制代码

总结:switch根据location.pathname,path,exact,strict,sensitive获取元素并返回element

第二步 Route react-router

var Route = function (_React$Component) {
  function Route() {
    var _temp, _this, _ret;
    //获取参数
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    //修改this
    return _ret = (
      _temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), 
      //检查当前元素是否符合match
      _this.state = {match: _this.computeMatch(_this.props,_this.context.router)},_temp),
       //这里是真正return
       _possibleConstructorReturn(_this, _ret); 
  }
  // 设置content
  Route.prototype.getChildContext = function getChildContext() {
    return {
      router: _extends({}, this.context.router, {
        route: {
          location: this.props.location || this.context.router.route.location,
          match: this.state.match
        }
      })
    };
  };
  // 根据参数检查当前元素是否符合匹配规则
  Route.prototype.computeMatch = function computeMatch(_ref, router) {
    var computedMatch = _ref.computedMatch,
        location = _ref.location,
        path = _ref.path,
        strict = _ref.strict,
        exact = _ref.exact,
        sensitive = _ref.sensitive;

    if (computedMatch) return computedMatch;

    var route = router.route;

    var pathname = (location || route.location).pathname;

    return matchPath(pathname, { path: path, strict: strict, exact: exact, sensitive: sensitive }, route.match);
  };
  // 设置match
  Route.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps, nextContext) {
    this.setState({
      match: this.computeMatch(nextProps, nextContext.router)
    });
  };

  Route.prototype.render = function render() {
    var match = this.state.match;
    var _props = this.props,
        children = _props.children,
        component = _props.component,
        render = _props.render;
    var _context$router = this.context.router,
        history = _context$router.history,
        route = _context$router.route,
        staticContext = _context$router.staticContext;

    var location = this.props.location || route.location;
    var props = { match: match, location: location, history: history, staticContext: staticContext };
    //检查route 是否有component组
    if (component) return match ? React.createElement(component, props) : null;  
    // 检查是否包含render 组件
    if (render) return match ? render(props) : null;
    // withRouter 使用的方式
    if (typeof children === "function") return children(props);

    if (children && !isEmptyChildren(children)) return React.Children.only(children);

    return null;
  };

  return Route;
}(React.Component);

复制代码

总结:route 渲染的方式: component render children,代码示例用的是component,route 是检查当前组件是否符合路由匹配规则并执行创建过程

第三步 HashRouter react-router-dom

import Router from './Router'
import {createHistory} from 'history'
var HashRouter = function (_React$Component) {
  function HashRouter() {
    var _temp, _this, _ret;
    //参数转换为数组
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {  
      args[_key] = arguments[_key];
    }
    return _ret = (
      _temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this),
       _this.history = createHistory(_this.props), _temp), //创建history
       _possibleConstructorReturn(_this, _ret);  //真正返回的东西 返回this
  }
  HashRouter.prototype.render = function render() {
    // 返回一个Router,并且把history,children传递给Router
    return React.createElement(Router, { history: this.history, children: this.props.children });
  };
  return HashRouter;
}(React.Component);
复制代码

总结 通过 history库里面 createHistory 创建路由系统

第四部 Router react-router

var Router = function (_React$Component) {
  function Router() {
    var _temp, _this, _ret;
    //获取参数,和其他组件一样
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
      match: _this.computeMatch(_this.props.history.location.pathname)  //返回路由对象
    }, _temp), _possibleConstructorReturn(_this, _ret);  //返回this
  }
  // 返回context
  Router.prototype.getChildContext = function getChildContext() {
    return {
      router: _extends({}, this.context.router, {
        history: this.props.history,
        route: {
          location: this.props.history.location,
          match: this.state.match
        }
      })
    };
  };
    
  Router.prototype.computeMatch = function computeMatch(pathname) {
    return {
      path: "/",
      url: "/",
      params: {},
      isExact: pathname === "/"
    };
  };

  Router.prototype.componentWillMount = function componentWillMount() {
    var _this2 = this;

    var _props = this.props,
        children = _props.children,
        history = _props.history;

    // 启动监听 当hash 改变是做一次检查,并返回unlisten 取消事件
    this.unlisten = history.listen(function () {
      _this2.setState({
        match: _this2.computeMatch(history.location.pathname)
      });
    });
  };
  //销毁前取消监听
  Router.prototype.componentWillUnmount = function componentWillUnmount() {
    this.unlisten();
  };
  // children是HashRouter 传递进来的
  Router.prototype.render = function render() {
    var children = this.props.children;
    return children ? React.Children.only(children) : null;
  };

  return Router;
}(React.Component);
复制代码

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

第五部 withRouter

var withRouter = function withRouter(Component) {
  var C = function C(props) {
   //获取props
    var wrappedComponentRef = props.wrappedComponentRef,
        remainingProps = _objectWithoutProperties(props, ["wrappedComponentRef"]);
    // Route 组件 children方式
    return React.createElement(Route, {
      children: function children(routeComponentProps) {
        // 这里使用的是route 组件 children(props)
        //routeComponentProps 实际等于 { match: match, location: location, history: history, staticContext: staticContext };
        return React.createElement(Component, _extends({}, remainingProps, routeComponentProps, {
          ref: wrappedComponentRef
        }));
      }
    });
  };

  C.displayName = "withRouter(" + (Component.displayName || Component.name) + ")";
  C.WrappedComponent = Component;
  // 该类似于object.assign(C,Component),得到的结果是C
  return hoistStatics(C, Component);
};
复制代码

到这里真个流程基本结束了,这只是react-router的一种使用方式的解析,本文的目的是理解react-router的运行机制,如果有什么错误还望指出,谢谢?

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/100884.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • mysql前缀索引及其选择「建议收藏」

    mysql前缀索引及其选择「建议收藏」有时候需要索引很长的字符列,比如BLOB、TEXT或者很长的VARCHAR类型的列,通常可以索引开始的部分字符,这样可以大大节约索引空间,从而提高索引效率。

    2022年5月23日
    35
  • Java 审计之xss审计要点

    Java审计之xss审计要点0x00前言上篇文章讲了xss的一个简单审计,这篇文章可以来复盘一下上篇文章内容在上篇文章基础上做一个详细说明,以及其他的一些审计姿势。首发:Java审计之XSS

    2021年12月12日
    262
  • RSA登录加密_rsa私钥加密公钥解密

    RSA登录加密_rsa私钥加密公钥解密随手记2本文章仅作学习参考使用,不做其他使用。​​​​​​网站:aHR0cHM6Ly9iZWlqaW5nLnR1aXR1aTk5LmNvbS9kZW5nbHUuaHRtbA==输入登录密码“123456”,分析抓包数据如下:返回了一个document类型的包,表单提交的方式,无法使用跟栈的方式定位加密方法,所以这里我使用搜索url的方式定位加密位置,如下:然后在全局搜索关键字“l_submit”,直接跟进加密方法里去,下断点开始调试得到了密码的明文数据,并且在下面也发…

    2022年9月3日
    2
  • java工厂模式三种详解(部分转载)

    java工厂模式三种详解(部分转载)工厂方法模式(FactoryMethod)工厂方法模式分为三种:1、普通工厂模式,就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。首先看下关系图:举例如下:(我们举一个发送邮件和短信的例子)首先,创建二者的共同接口:[java]viewplaincopypublicinterfaceSender{ publicvoidSe…

    2022年7月20日
    12
  • linux压缩命令常用:tar,tgz,gzip,zip,rar

    linux压缩命令常用:tar,tgz,gzip,zip,rarlinux压缩命令常用的有三个:tar,tgz,gzip,zip一,tar(一)tar压缩命令tar-cvfexamples.tarfiles|dir#说明:-c,–createcreateanewarchive创建一个归档文件-v,–verboseverboselylistfilesprocessed显示创建归档文件的进程-f,…

    2022年5月9日
    57
  • google search_google.com

    google search_google.comgson中字符串转换为json数据:StringtestString=”‘bgColorPc ‘:’red'”;JsonObjectjsondetail=newJsonParser().parse(testString).getAsJsonObject();StringbgColorPc=jsondetail.get(“bgColorPc”).getAsStrin

    2022年8月23日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号