Reputation: 570
I'm trying to detect a route change caused by clicking on a <Link>
, so that I can change the state of my component when the route changes. I've seen a lot of places suggest that you can use router.addTransitionHook
, but I have a couple problems with this.
addTransitionHook
, and it sounds like it might have been replaced.context.router
in the constructor. I've tried everything suggested here (i.e. Component.contextTypes = { router: React.PropTypes.func.isRequired }
) and I'm not getting anything except undefined
for my context.router
. Do I need to do something when I create the router in order for the components to have access to context
?There are a couple proposed solutions that involve mixins. The Lifecycle Mixin provides access to routerWillLeave
. That seems like what I want, but mixins aren't available in ES6 classes.
Maybe I should try defining onEnter
when I create the router as described here, but I'd rather not have to add any code to the router declaration. That doesn't seem like a good solution.
tldr; What's the best way to detect a React route change in an ES6 class?
Upvotes: 2
Views: 738
Reputation: 457
history.listenBefore is not supported in React Router V4. Instead use history.block for blocking transition. And history.listen((location, action) => { // do something })
for listening to route transition . Check the docs here history
Upvotes: 1
Reputation: 570
I never figured out how to use events to solve my problem, but I realized what I should be doing is using lifecycle methods instead. My route was <Route name="routename" component={RouteApp} path="/routename/:urlKey" />
. What I really cared about was when the urlKey
param changed, and when that happens, the props of your component will change. Thus, I was able to put the code inside the componentWillReceiveProps
lifecycle method.
Upvotes: 0
Reputation: 8276
If I understood you correctly you want to use listenBefore
function from History module.
So you could use it like:
history.listenBefore((location) => {
// ...
});
or if you need to transition asynchronously, then:
history.listenBefore((location, callback) => {
// ...
});
Check for more in the Confirming Navigation docs.
Upvotes: 0