React实现类似Vue的路由监听Hook
- 监听路由变化;
- React Hook封装,返回回调函数,新旧路由为函数参数;
代码
import { useEffect, useRef } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
const useRouteChange = (callback: (prevLocation: string, newLocation: string) => void) => {
const location = useLocation();
const history = useHistory();
const prevLocation = useRef(location.pathname);
useEffect(() => {
const unListen = history.listen(newLocation => {
callback(prevLocation.current, newLocation.pathname);
prevLocation.current = newLocation.pathname;
});
return () => {
unListen();
};
}, [history, callback]);
};
export default useRouteChange;
使用
const routeChange = useCallback((prevLocation, newLocation) => {
console.log(`RouteChange:From ${prevLocation} To ${newLocation}`);
}, []);
useRouteChange(routeChange);