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";@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);
新聞熱點
疑難解答
圖片精選