React router 4 history.listen never fires

后端 未结 2 1170
别那么骄傲
别那么骄傲 2021-01-01 18:19

Switched to router v4 and history v4.5.1 and now history listener not working

import createBrowserHistory from \'history/createBrowserHistory\'
const history         


        
相关标签:
2条回答
  • 2021-01-01 18:47

    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.

    0 讨论(0)
  • 2021-01-01 18:50

    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)

    0 讨论(0)
提交回复
热议问题