React router 4 history.listen never fires

Switch to v4 router and v4.5.1 history, and now the history listener is not working

import createBrowserHistory from 'history/createBrowserHistory' const history = createBrowserHistory() history.listen((location, action) => { console.log(action, location.pathname, location.state) // <=== Never happens }) render( <Provider store={store}> <Router history={history}> ... </Router> </Provider>, document.getElementById('root') ) 

Any ideas why ignore it?

+7
reactjs redux react-router browser-history react-router-v4
source share
2 answers

Since you are using BrowserRouter (with importing the Router alias, as mentioned in the comments on the question), you do not need the story you are going through. Instead, internally creates and assigns a new browser history to the router . So the instance of the story you are listening to and using on the Router is not the same. This is why your listener is not working.

Import the original router.

 import { Router } from 'react-router-dom'; 

It will work as you expect.

+4
source share

The problem is that you create your own history object and pass it to the router. However, React Router v4 already provides this object for you through this.props . (Importing a router is irrelevant)

 componentDidMount() { this.props.history.listen((location, action) => console.log('History changed!', location, action)); } 

You may need to overlay your application a bit, as shown below, and put this componentDidMount method in MyApp.jsx , rather than right at the top level.

 <Provider store={store}> <BrowserRouter> <MyApp/> </BrowserRouter> </Provider> 

(Or use NativeRouter instead of BrowserRouter if you are doing React Native)

0
source share

All Articles