React router 4 history.listen never fires

2019-04-05 16:15发布

Switched to router v4 and history v4.5.1 and now history listener 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 it is being ignored?

2条回答
We Are One
2楼-- · 2019-04-05 16:33

Since you are using BrowserRouter(with import alias Router as mentioned in comments of the question), it doesn't care the history prop you pass in. Instead of that it internally creates and assigns new browser history to the Router. So the history instance that you listen and being used in Router is not the same. That's why your listener doesn't work.

Import the original Router.

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

It will work as you expect.

查看更多
Root(大扎)
3楼-- · 2019-04-05 16:39

The problem is that you are creating your own history object and passing it into the router. However, React Router v4 already provides this object for you, via this.props. (Importing Router has nothing to do with this)

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

You may need to layer your app a bit more though, like below, and put this componentDidMount method in your MyApp.jsx and not directly at the very top level.

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

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

查看更多
登录 后发表回答