I've a react component that listens to route changes using browserHistory's listen method. After registering a handler with
browserHistory.listen(this.handleRouteChanged)
in ComponentDidMount, how do I remove the listener in componentWillUnmount?
I can't find any documentation on this, and searching through github issues I've found suggestions using browserHistory.unregisterTransitionHook which doesn't seem to remove the listener, and in addition seems to be deprecated.
Any ideas?
The listen()
method returns a function that will stop it from listening. This is documented on the history docs:
A "history" encapsulates navigation between different screens in your app, and notifies listeners when the current screen changes.
import { createHistory } from 'history' const history = createHistory() // Get the current location const location = history.getCurrentLocation() // Listen for changes to the current location const unlisten = history.listen(location => { console.log(location.pathname) }) // Push a new entry onto the history stack history.push({ pathname: '/the/path', search: '?a=query', // Extra location-specific state may be kept in session // storage instead of in the URL query string! state: { the: 'state' } }) // When you're finished, stop the listener unlisten()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With