用于分析的屏幕跟踪
编辑页面
了解在使用 Expo Router 时如何启用分析的屏幕跟踪。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
与 React Navigation 不同,Expo Router 始终可以访问 URL。这意味着屏幕跟踪和 Web 一样简单。
- 创建一个高阶组件,用于观察当前选中的 URL
- 在你的分析提供商中跟踪该 URL
srcapp_layout.tsxsrc/app/_layout.tsx
import { useEffect } from 'react'; import { usePathname, useGlobalSearchParams, Slot } from 'expo-router'; export default function Layout() { const pathname = usePathname(); const params = useGlobalSearchParams(); // 在你的分析提供商中跟踪此处的位置。 useEffect(() => { analytics.track({ pathname, params }); }, [pathname, params]); // 以最基本的方式导出所有子路由。 return <Slot />; }
现在,当用户切换路由时,分析提供商将收到通知。
从 React Navigation 迁移
React Navigation 的屏幕跟踪指南无法像 Expo Router 那样对导航状态做出相同的假设。因此,实现需要使用 onReady 和 onStateChange 回调。尽可能避免使用这些方法,因为根 <NavigationContainer /> 并不会直接暴露,并且在 Expo Router 中支持级联。