Use useHistory().listen to monitor route changes
When using react's function components, sometimes we want to monitor routing changes and perform certain operations when routing changes, so we need to use it useHistory().listen
to achieve.
Here's how to use it
const history = useHistory();
useEffect(() => {
const unlisten = history.listen((historyLocation) => {
cnosole.log(historyLocation)
});
return () => {
unlisten();
};
}, [history]);
It should be noted here that this method useEffect
should be returned listen
and uninstalled. If written in the following form
const history = useHistory();
useEffect(() => {
history.listen((historyLocation) => {
cnosole.log(historyLocation)
});
}, [history]);
It will cause listen
the method to be mounted all the time. Even if the current component has been destroyed or the page has been jumped, this method will always monitor the change of the route. Whenever the route changes, the inside will be cnosole.log
executed along with it.