Cannot read property 'history' of undefined (useHistory hook of React Router 5)

前端 未结 6 1442
离开以前
离开以前 2020-12-17 08:14

I am using the new useHistory hook of React Router, which came out a few weeks ago. My React-router version is 5.1.2. My React is at version 16.10.1. You can find my code at

相关标签:
6条回答
  • 2020-12-17 08:28

    Note to other people that run into this problem and already have wrapped the component with Router component. Make sure that Router and the useHistory hook are imported from the same package. The same error can be thrown when one of them are imported from react-router and the other one from react-router-dom and the package versions of those packages don't match. Don't use both of them, read about the difference here.

    0 讨论(0)
  • 2020-12-17 08:31

    useHistory won't work in the component where you have your Routes because the context which is needed for useHistory is not yet set.

    useHistory will work on any child component or components which your have declared in your Router but it won't work on Router's parent component or Router component itself.

    0 讨论(0)
  • 2020-12-17 08:32

    Its because the react-router context isn't set in that component. Since its the <Router> component that sets the context you could use useHistory in a sub-component, but not in that one.

    0 讨论(0)
  • 2020-12-17 08:36

    I updated my react-router-dom from 5.0.0 to ^5.1.2 and it's been solved. You may notice that the useHistory is in a sub-component.

    0 讨论(0)
  • 2020-12-17 08:39

    The solution is:

    in the Main (father) component

    import { BrowserRouter } from "react-router-dom";
    
    <BrowserRouter><App /></BrowserRouter>
    

    in the child component (App)

    import { withRouter } from "react-router-dom";
    
    
    function App(props) {
        const { i18n } = useTranslation();
        const { language } = useContext(AppContext);
        let history = useHistory();
    
        useEffect(() => {
            i18n.changeLanguage(language);
        }, []);
    
        return(
    
                <Route path="/">
                    <div className={testClass}>HEADER</div>
                </Route>
    
        )
    }
    
    export default withRouter(App);
    
    0 讨论(0)
  • 2020-12-17 08:41

    Use BrowserRouter.

    import {
      BrowserRouter as Router,
      Route,
      Switch,
    } from 'react-router-dom';
    

    If you use Router, then you need to specify a history for it:

    import {
      Router,
      Route,
      Switch,
    } from 'react-router-dom';
    import createBrowserHistory from 'history';
    
    const history = createBrowserHistory();
    return (
      <Router history={history} >
        ...
      </Router>
    );
    
    0 讨论(0)
提交回复
热议问题