React实现类似Vue的路由监听Hook
- 监听路由变化;
- React Hook封装,返回回调函数,新旧路由为函数参数;
代码
javascript
import { useEffect, useRef } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
/**
* 监听路由变化
* @param callback
*/
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;
使用
javascript
const routeChange = useCallback((prevLocation, newLocation) => {
console.log(`RouteChange:From ${prevLocation} To ${newLocation}`);
}, []);
useRouteChange(routeChange);