Navigating Programmatically in React-Router v4

后端 未结 10 1121
后悔当初
后悔当初 2020-12-02 11:16

I couldn\'t wait and I jumped into using the latest alpha version of react-router v4. The all-new is great in keeping your U

10条回答
  •  自闭症患者
    2020-12-02 11:49

    If you need to access history outside of components (for example in redux actions) react-router has published their original solution here.

    Basically you have to create your own history object:

    import { createBrowserHistory } from 'history';
    
    const history = createBrowserHistory();
    

    And pass it to your router:

    import { Router } from 'react-router-dom';
    
    ReactDOM.render((
       // <<-- the history object
        
      
    ), document.getElementById('root'))
    

    Note: you have to use plain Router instead of BrowserRouter or HashRouter here!

    If you export the history now, you can work with it anywhere:

    import history from './history';
    
    history.push('/home');
    

提交回复
热议问题