How to Access History Object Outside of a React Component

后端 未结 3 1164
南方客
南方客 2020-12-15 03:34

First of all, I am pretty familiar with the withRouter HoC, however, in this case, it doesn\'t help because I do not want to access the history object in a comp

3条回答
  •  北海茫月
    2020-12-15 04:24

    react-router v4 also provides a way to share history via the history package, namely createBrowserHistory() function.

    The important part is to make sure that the same history object is shared across your app. To do that you can take advantage of the fact that node modules are singletons.

    Create a file called history.js in your project, with the following content:

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

    You can then just import it in your application via:

    import history from "./history.js";
    

    Please note that only Router accepts the history prop (BrowserRouter does not), so be sure to update your router JSX accordingly:

    import { Router } from "react-router-dom";
    import history from "./history.js";
    
    // and then in your JSX:
    return (
      
        {/* routes as usuall */}
      
    )
    

    A working example can be found at https://codesandbox.io/s/owQ8Wrk3

提交回复
热议问题