React router 4 history.listen never fires

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?


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.


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)

链接地址: http://www.djcxy.com/p/96320.html

上一篇: 最快的方法可以将数千张图像读入一个大的numpy阵列

下一篇: 反应路由器4 history.listen永远不会引发火灾