用于分析的屏幕追踪
要追踪当前活跃的屏幕,我们需要
- 添加一个回调以获取状态更改通知
- 获取根导航器状态并找到活动路由名称
要获取状态更改通知,我们可以使用 `NavigationContainer` 上的 `onStateChange` 属性。要获取根导航器状态,我们可以使用容器 ref 上的 `getRootState` 方法。请注意,`onStateChange` 不会在初始渲染时调用,因此您必须单独设置初始屏幕。
示例
此示例展示了如何将此方法适配到任何移动分析 SDK。
- 静态
- 动态
import {
createStaticNavigation,
useNavigationContainerRef,
useNavigation,
} from '@react-navigation/native';
export default function App() {
const navigationRef = useNavigationContainerRef();
const routeNameRef = React.useRef();
return (
<Navigation
ref={navigationRef}
onReady={() => {
routeNameRef.current = navigationRef.current.getCurrentRoute().name;
}}
onStateChange={async () => {
const previousRouteName = routeNameRef.current;
const currentRouteName = navigationRef.current.getCurrentRoute().name;
const trackScreenView = () => {
// Your implementation of analytics goes here!
};
if (previousRouteName !== currentRouteName) {
// Replace the line below to add the tracker from a mobile analytics SDK
await trackScreenView(currentRouteName);
}
// Save the current route name for later comparison
routeNameRef.current = currentRouteName;
}}
/>
);
}
import {
NavigationContainer,
useNavigation,
useNavigationContainerRef,
} from '@react-navigation/native';
export default function App() {
const navigationRef = useNavigationContainerRef();
const routeNameRef = React.useRef();
return (
<NavigationContainer
ref={navigationRef}
onReady={() => {
routeNameRef.current = navigationRef.current.getCurrentRoute().name;
}}
onStateChange={async () => {
const previousRouteName = routeNameRef.current;
const currentRouteName = navigationRef.current.getCurrentRoute().name;
const trackScreenView = () => {
// Your implementation of analytics goes here!
};
if (previousRouteName !== currentRouteName) {
// Replace the line below to add the tracker from a mobile analytics SDK
await trackScreenView(currentRouteName);
}
// Save the current route name for later comparison
routeNameRef.current = currentRouteName;
}}
>
{/* ... */}
</NavigationContainer>
);
}