侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

浅谈[email protected] 使用方法和源码分析

前端  /  管理员 发布于 5年前   408

[email protected] || [email protected]

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 = () => ( 
{ router.map(({component,path,exact},index)=>{ return }) }
);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 (          , document.getElementById ('App'));

home.js

import { withRouter } from "react-router-dom";@withRouterclass Home extends React.Component { constructor(props: PropsType) {  super(props);  this.state = {}; } goPath=()=>{   this.props.history.push('/home') } render() {  return (   
home ); }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的运行机制,如果有什么错误还望指出,谢谢

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

您可能感兴趣的文章:

  • 深入理解[email protected] 使用和源码解析


  • 上一条:
    模块化react-router配置方法详解
    下一条:
    ES6中字符串的使用方法扩展
  • 昵称:

    邮箱:

    1条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 使用 Alpine.js 排序插件对元素进行排序(0个评论)
    • 在js中使用jszip + file-saver实现批量下载OSS文件功能示例(0个评论)
    • 在vue中实现父页面按钮显示子组件中的el-dialog效果(0个评论)
    • 使用mock-server实现模拟接口对接流程步骤(0个评论)
    • vue项目打包程序实现把项目打包成一个exe可执行程序(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-03
    • 2018-04
    • 2018-05
    • 2018-06
    • 2018-09
    • 2018-11
    • 2018-12
    • 2019-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客