To solve the problem that react-router/react-router-dom v4 history cannot be accessed,
Preface
Recently I upgraded react-router. When using react-router-dom, the sub-component uses this. props. history cannot be found. Check the official documentation and I haven't found it for a long time, because I jumped to the page only after the asynchronous execution. I need to use push or replace. What should I do, domestic knowledge is what you copy me. I copy yours and it's all spam. Only Google,
Finally, I found the answer: (check the code at a Glance)
Solution
First use 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 '; // This is loaded on demand. 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> );};}
The next step is the use of history for child components.
Import React, {Component} from 'react '; // In this step, you need npm, import PropTypes from 'prop-types '; export default class Hello extends Component {constructor (props) {super (props);} // This step focuses on 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 </button> </div> );};}
Let's take a look at this. context:
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.