import warning from"warning";import React from"react";import PropTypes from"prop-types";import { createBrowserHistory as createHistory } from"history";//这里的history就是上面第二个例子中的historyModuleimport Router from"./Router"; //对应第二个例子中的Router对象/** * The public API for a <Router> that uses HTML5 history. //这里是重点 */classBrowserRouterextendsReact.Component { history =createHistory(this.props);render() {return <Routerhistory={this.history} children={this.props.children} />; }}exportdefault BrowserRouter;//定义一个接口exportinterfaceHistory { length:number; action:Action; location:Location;push(path:Path, state?:LocationState):void;push(location:LocationDescriptorObject):void;replace(path:Path, state?:LocationState):void;replace(location:LocationDescriptorObject):void;go(n:number):void;goBack():void;goForward():void;block(prompt?:boolean):UnregisterCallback;listen(listener:LocationListener):UnregisterCallback;createHref(location:LocationDescriptorObject):Href;}/** * The public API for putting history on context. //这里的道理类似于例子二中第二步 */classRouterextendsReact.Component {static childContextTypes = { router:PropTypes.object.isRequired };getChildContext() {return { router: {...this.context.router, history:this.props.history, route: { location:this.props.history.location, match:this.state.match } } }; } state = { match:this.computeMatch(this.props.history.location.pathname) };computeMatch(pathname) {return { path:"/", url:"/", params: {}, isExact: pathname ==="/" }; }componentWillMount() {const { children,history } =this.props;// Do this here so we can setState when a <Redirect> changes the// location in componentWillMount. This happens e.g. when doing// server rendering using a <StaticRouter>.this.unlisten =history.listen(() => {this.setState({ match:this.computeMatch(history.location.pathname) }); }); }componentWillReceiveProps(nextProps) {warning(this.props.history ===nextProps.history,"You cannot change <Router history>" ); }componentWillUnmount() {this.unlisten(); }render() {const { children } =this.props;return children ?React.Children.only(children) :null; }}exportdefault Router;