Você pode usar a history.listen()função ao tentar detectar a mudança de rota. Considerando que você está usando react-router v4, envolva seu componente com withRouterHOC para obter acesso ao historyprop.
history.listen()retorna uma unlistenfunção. Você usaria isso para unregisterouvir.
Você pode configurar suas rotas como
index.js
ReactDOM.render(
<BrowserRouter>
<AppContainer>
<Route exact path="/" Component={...} />
<Route exact path="/Home" Component={...} />
</AppContainer>
</BrowserRouter>,
document.getElementById('root')
);
e então em AppContainer.js
class App extends Component {
componentWillMount() {
this.unlisten = this.props.history.listen((location, action) => {
console.log("on route change");
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<div>{this.props.children}</div>
);
}
}
export default withRouter(App);
Dos documentos de história :
Você pode ouvir as alterações no local atual usando
history.listen:
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
O objeto location implementa um subconjunto da interface window.location, incluindo:
**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment
Os locais também podem ter as seguintes propriedades:
location.state - algum estado extra para este local que não reside no URL (compatível com createBrowserHistorye
createMemoryHistory)
location.key- Uma string única que representa este local (compatível com createBrowserHistoryecreateMemoryHistory )
A ação PUSH, REPLACE, or POPdepende de como o usuário chegou ao URL atual.
Quando você está usando o react-router v3, você pode fazer uso history.listen()do historypacote como mencionado acima ou você também pode fazer usobrowserHistory.listen()
Você pode configurar e usar suas rotas como
import {browserHistory} from 'react-router';
class App extends React.Component {
componentDidMount() {
this.unlisten = browserHistory.listen( location => {
console.log('route changes');
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<Route path="/" onChange={yourHandler} component={AppContainer}>
<IndexRoute component={StaticContainer} />
<Route path="/a" component={ContainerA} />
<Route path="/b" component={ContainerB} />
</Route>
)
}
}