淺談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 源碼解析
下面代碼中會(huì)移除部分的類型檢查和提醒代碼,突出重點(diǎn)代碼
第一步 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() {
//使用傳遞進(jìn)來(lái)的組件覆蓋本身
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不會(huì)進(jìn)入該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;
//檢查當(dāng)前配置是否符合,
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);
總結(jié):switch根據(jù)location.pathname,path,exact,strict,sensitive獲取元素并返回element
第二步 Route react-router
var Route = function (_React$Component) {
function Route() {
var _temp, _this, _ret;
//獲取參數(shù)
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),
//檢查當(dāng)前元素是否符合match
_this.state = {match: _this.computeMatch(_this.props,_this.context.router)},_temp),
//這里是真正return
_possibleConstructorReturn(_this, _ret);
}
// 設(shè)置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
}
})
};
};
// 根據(jù)參數(shù)檢查當(dāng)前元素是否符合匹配規(guī)則
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);
};
// 設(shè)置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);
總結(jié):route 渲染的方式: component render children,代碼示例用的是component,route 是檢查當(dāng)前組件是否符合路由匹配規(guī)則并執(zhí)行創(chuàng)建過(guò)程
第三步 HashRouter react-router-dom
import Router from './Router'
import {createHistory} from 'history'
var HashRouter = function (_React$Component) {
function HashRouter() {
var _temp, _this, _ret;
//參數(shù)轉(zhuǎn)換為數(shù)組
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), //創(chuàng)建history
_possibleConstructorReturn(_this, _ret); //真正返回的東西 返回this
}
HashRouter.prototype.render = function render() {
// 返回一個(gè)Router,并且把history,children傳遞給Router
return React.createElement(Router, { history: this.history, children: this.props.children });
};
return HashRouter;
}(React.Component);
總結(jié) 通過(guò) history庫(kù)里面 createHistory 創(chuàng)建路由系統(tǒng)
第四部 Router react-router
var Router = function (_React$Component) {
function Router() {
var _temp, _this, _ret;
//獲取參數(shù),和其他組件一樣
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) //返回路由對(duì)象
}, _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;
// 啟動(dòng)監(jiān)聽(tīng) 當(dāng)hash 改變是做一次檢查,并返回unlisten 取消事件
this.unlisten = history.listen(function () {
_this2.setState({
match: _this2.computeMatch(history.location.pathname)
});
});
};
//銷毀前取消監(jiān)聽(tīng)
Router.prototype.componentWillUnmount = function componentWillUnmount() {
this.unlisten();
};
// children是HashRouter 傳遞進(jìn)來(lái)的
Router.prototype.render = function render() {
var children = this.props.children;
return children ? React.Children.only(children) : null;
};
return Router;
}(React.Component);
總結(jié) history是一個(gè)JavaScript庫(kù),可讓您在JavaScript運(yùn)行的任何地方輕松管理會(huì)話歷史記錄。history抽象出各種環(huán)境中的差異,并提供最小的API,使您可以管理歷史堆棧,導(dǎo)航,確認(rèn)導(dǎo)航以及在會(huì)話之間保持狀態(tài)。
第五部 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 實(shí)際等于 { 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),得到的結(jié)果是C
return hoistStatics(C, Component);
};
到這里真?zhèn)€流程基本結(jié)束了,這只是react-router的一種使用方式的解析,本文的目的是理解react-router的運(yùn)行機(jī)制,如果有什么錯(cuò)誤還望指出,謝謝
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React使用Electron開發(fā)桌面端的詳細(xì)流程步驟
React是一個(gè)流行的JavaScript庫(kù),用于構(gòu)建Web應(yīng)用程序,結(jié)合Electron框架,可以輕松地將React應(yīng)用程序打包為桌面應(yīng)用程序,本文詳細(xì)介紹了使用React和Electron開發(fā)桌面應(yīng)用程序的步驟,需要的朋友可以參考下2023-06-06
react滾動(dòng)加載useInfiniteScroll?詳解
使用useInfiniteScroll?hook可以處理檢測(cè)用戶何時(shí)滾動(dòng)到頁(yè)面底部的邏輯,并觸發(fā)回調(diào)函數(shù)以加載更多數(shù)據(jù),它還提供了一種簡(jiǎn)單的方法來(lái)管理加載和錯(cuò)誤消息的狀態(tài),今天通過(guò)實(shí)例代碼介紹下react滾動(dòng)加載useInfiniteScroll?相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2023-09-09
淺談使用React.setState需要注意的三點(diǎn)
本篇文章主要介紹了淺談使用React.setState需要注意的三點(diǎn),提出了三點(diǎn)對(duì) React 新手來(lái)說(shuō)是很容易忽略的地方,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
React中useTransition鉤子函數(shù)的使用詳解
React?18的推出標(biāo)志著React并發(fā)特性的正式到來(lái),其中useTransition鉤子函數(shù)是一個(gè)重要的新增功能,下面我們就來(lái)學(xué)習(xí)一下useTransition鉤子函數(shù)的具體使用吧2024-02-02
React報(bào)錯(cuò)之組件不能作為JSX組件使用的解決方法
本文主要介紹了React報(bào)錯(cuò)之組件不能作為JSX組件使用的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
React高級(jí)指引之Refs and the DOM使用時(shí)機(jī)詳解
在典型的React數(shù)據(jù)流中,props是父組件與子組件交互的唯一方式。要修改一個(gè)子組件,你需要使用新的props來(lái)重新渲染它。但是,在某些情況下,你需要在典型數(shù)據(jù)流之外強(qiáng)制修改子組件2023-02-02

