React Router v6如何实现路由追踪?原v5自定义方案不再适用
React Router v6 路由追踪实现方案
方案一:用useLocation监听路由变化
通过useLocation获取当前路由信息,配合useEffect监听路径变化触发追踪逻辑,可封装成自定义Hook复用:
import { useLocation, useEffect } from 'react-router-dom'; const useRouteTracking = () => { const location = useLocation(); useEffect(() => { // 可通过路由映射表匹配追踪标题 const trackTitle = getTrackTitleByPath(location.pathname); doTrackingThings(trackTitle); }, [location.pathname]); // 仅在路由路径变化时执行 }; // 路由-标题映射表示例 const routeTitleMap = { '/path/home': '首页', '/path/contact': '联系我们' }; const getTrackTitleByPath = (path) => { return routeTitleMap[path] || '未知页面'; };
在根组件中调用Hook实现全局监听:
function App() { useRouteTracking(); return ( <Routes> <Route path="/path/home" element={<Home />} /> <Route path="/path/contact" element={<Contact />} /> </Routes> ); }
方案二:给路由元素包裹追踪高阶组件
针对特定路由单独配置追踪信息,可封装高阶组件包裹路由的element:
import { useLocation, useEffect } from 'react-router-dom'; const withTracking = (Component, trackTitle) => { return (props) => { const location = useLocation(); useEffect(() => { doTrackingThings(trackTitle); }, [location.pathname, trackTitle]); return <Component {...props} />; }; };
使用方式:
<Routes> <Route path="/path/home" element={<HomeWithTracking />} /> <Route path="/path/contact" element={<ContactWithTracking />} /> </Routes> // 生成带追踪逻辑的组件 const HomeWithTracking = withTracking(Home, '首页'); const ContactWithTracking = withTracking(Contact, '联系我们');
方案三:结合导航事件做精细追踪
利用useNavigationType获取导航类型(POP/PUSH/REPLACE),配合useLocation实现更详细的追踪:
import { useLocation, useNavigationType, useEffect } from 'react-router-dom'; const useAdvancedRouteTracking = () => { const location = useLocation(); const navigationType = useNavigationType(); useEffect(() => { const trackTitle = getTrackTitleByPath(location.pathname); doTrackingThings({ title: trackTitle, path: location.pathname, navigationType: navigationType, timestamp: Date.now() }); }, [location.pathname, navigationType]); };
在根组件调用该Hook即可启用高级追踪。
注意事项
- 若路由含动态参数(如
/user/:id),需在映射表中处理动态路径,或结合location.pathname与location.params生成追踪标题。 - 建议给
doTrackingThings添加防抖/节流逻辑,避免快速切换路由时频繁触发。
内容的提问来源于stack exchange,提问作者Michael Johansen
相关产品推荐
相关产品推荐

