使用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方法一直挂载,即便当前组件已经销毁或页面已经跳转,这个方法也会一直监听路由的变化,每当路由发生改变,里面的console.log就会跟着执行一边。
本文介绍了如何在React函数组件中使用useHistory().listen监听路由变化,强调了正确的用法,即确保在useEffect返回中卸载监听器,避免资源泄露。
2761





