首先使用router
import React, { Component } from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import { Provider } from 'mobx-react'; import stores from '../store/index'; import Bundle from '../components/bundle'; import Hello from 'bundle-loader?lazy!../components/hello.jsx'; // 这是按需加载,对于现在讨论的问题没有影响 const HelloAPP = () => ( <Bundle load={Hello}> {(Hello) => <Hello />} </Bundle> ); export default class App extends Component { constructor(props) { super(props); } render() { return ( <Provider { ...stores }> <BrowserRouter basename="/"> <Route path="/" component={HelloAPP}/> </BrowserRouter> </Provider> ); }; }
接着是子组件的使用history
import React, { Component } from 'react'; // 需要这步,你要npm 这个, import PropTypes from 'prop-types'; export default class Hello extends Component { constructor(props) { super(props); } // 这一步是重点 static contextTypes = { router: PropTypes.object.isRequired }; test = () => { console.log(this.context); setTimeout(() => { this.context.router.history.push("/otherPath"); }, 1000); }; render() { return ( <div> <button onClick={this.test}>按钮</button> </div> ); }; }
让我们看看this.context :