使用useHistory().listen监听路由变化

使用useHistory().listen监听路由变化

在使用react的函数组件时,有时候我们会想监听路由变化,并在路由变化时进行某些操作,就需要使用useHistory().listen来实现了。
下面是使用方法

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

这里要注意useEffect要返回listen这个方法,将其卸载。如果写成下面这种形式 

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

会导致listen方法一直挂载,即便当前组件已经销毁或页面已经跳转,这个方法也会一直监听路由的变化,每当路由发生改变,里面的cnosole.log就会跟着执行一边。

猜你喜欢

转载自blog.csdn.net/wsdshdhdhd/article/details/126873316