了解如何在使用 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.
创建一个高阶组件来观察当前选定的 URL
¥Create a higher-order component that observes the currently selected URL
跟踪你的分析提供商中的 URL
¥Track the URL in your analytics provider
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.
¥Migrating from React Navigation
React Navigation 的 屏幕跟踪指南 无法对 Expo Router 所做的导航状态做出相同的假设。因此,实现需要使用 onReady
和 onStateChange
回调。如果可能,请避免使用这些方法,因为根 <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.