Use useHistory().listen to monitor route changes

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().listento 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 useEffectshould be returned listenand uninstalled. If written in the following form 

const history = useHistory();
useEffect(() => {
    history.listen((historyLocation) => {
        cnosole.log(historyLocation)
    });
}, [history]);

It will cause listenthe 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.logexecuted along with it.

Guess you like

Origin blog.csdn.net/wsdshdhdhd/article/details/126873316