When component is specified as <Route>
's component
property, React Router 4 (RR4) passes to it few additional properties: match
, location
and history
.
Then u should use componentDidUpdate
lifecycle method to compare location
objects before and after update (remember ES object comparison rules). Since location objects are immutable, they will never match. Even if u navigate to the same location.
componentDidUpdate(newProps) {
if (this.props.location !== newProps.location) {
this.handleNavigation();
}
}
withRouter
should be used when you need to access these properties within an arbitrary component that is not specified as a component
property of any Route. Make sure to wrap your app in <BrowserRouter>
since it provides all the necessary API, otherwise these methods will only work in components contained within <BrowserRouter>
.
There are cases when user decides to reload the page via navigation buttons instead of dedicated interface in browsers. But comparisons like this:
this.props.location.pathname !== prevProps.location.pathname
will make it impossible.