用于分析的屏幕跟踪

了解如何在使用 Expo Router 时启用屏幕跟踪以进行分析。


与 React Navigation 不同,Expo Router 总是能够访问 URL。这意味着屏幕跟踪就像在网页上一样简单。

🌐 Unlike React Navigation, Expo Router always has access to a URL. This means screen tracking is as easy as the web.

  1. 创建一个高阶组件来观察当前选定的 URL
  2. 跟踪你的分析提供商中的 URL
app
_layout.tsx
app/_layout.tsx
import { useEffect } from 'react'; import { usePathname, useGlobalSearchParams, Slot } from 'expo-router'; export default function Layout() { const pathname = usePathname(); const params = useGlobalSearchParams(); // Track the location in your analytics provider here. useEffect(() => { analytics.track({ pathname, params }); }, [pathname, params]); // Export all the children routes in the most basic way. return <Slot />; }

现在,当用户更改路由时,分析提供商将收到通知。

🌐 Now when the user changes routes, the analytics provider will be notified.

从 React 导航迁移

🌐 Migrating from React Navigation

React Navigation 的 屏幕跟踪指南 无法像 Expo Router 那样对导航状态做出相同的假设。因此,实现需要使用 onReadyonStateChange 回调。如果可能的话,请尽量避免使用这些方法,因为根 <NavigationContainer /> 没有直接暴露,并且在 Expo Router 中允许级联。

🌐 React Navigation's screen tracking guide cannot make the same assumptions about the navigation state that Expo Router can. As a result, the implementation requires the use of onReady and onStateChange callbacks. Avoid using these methods if possible as the root <NavigationContainer /> is not directly exposed and allows cascading in Expo Router.