麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > JavaScript > 正文

淺談[email protected] 使用方法和源碼分析

2019-11-19 11:24:18
字體:
來源:轉載
供稿:網友

[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 = () => ( <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";@withRouterclass 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 <react-router>

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的運行機制,如果有什么錯誤還望指出,謝謝

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 国产五区| 91羞羞 | 欧美日韩在线视频一区 | 国产小视频在线 | 精品中文字幕久久久久四十五十骆 | 55夜色66夜色国产精品视频 | 久久亚洲国产精品 | 成人国产精品一区二区毛片在线 | 国产精品av久久久久久久久久 | 免费在线观看午夜视频 | 黄色小视频在线免费看 | 亚洲日本韩国精品 | 一级黄色欧美 | 99视频有精品视频高清 | 午夜精品成人 | av国产片| 色天天综合网 | 911色_911色sss主站色播 | 精品一区二区三区免费毛片 | 久久伊| 欧美一级高潮 | 毛片在线视频观看 | 深夜影院一级毛片 | 七首小情歌泰剧在线播放 | 日本在线视频一区二区三区 | 99最新网址 | 久久99精品久久久久久秒播放器 | 精品久久久久久久久久久aⅴ | 美女扒开腿让男生桶爽网站 | 欧美性受ⅹ╳╳╳黑人a性爽 | 黄色免费小视频网站 | 成人精品一区二区三区中文字幕 | 日本一区二区高清不卡 | 久久精品视频一区二区 | 美女久久久久 | 色网站免费观看 | 久久恋 | 最近日本电影hd免费观看 | 91精品国产91久久久久久蜜臀 | 黄色毛片免费视频 | 中文字幕亚洲一区二区三区 |