用于分析的屏幕跟踪
要跟踪当前活动的屏幕,我们需要:
¥To track the currently active screen, we need to:
-
添加回调以获取状态更改通知
¥Add a callback to get notified of state changes
-
获取根导航器状态并查找活动路由名称
¥Get the root navigator state and find the active route name
要获得状态更改的通知,我们可以在 NavigationContainer 上使用 onStateChange 属性。要获取根导航器状态,我们可以在容器的引用上使用 getRootState 方法。请注意,初始渲染时不会调用 onStateChange,因此你必须单独设置初始屏幕。
¥To get notified of state changes, we can use the onStateChange prop on NavigationContainer. To get the root navigator state, we can use the getRootState method on the container's ref. Please note that onStateChange is not called on initial render so you have to set your initial screen separately.
示例
¥Example
此示例展示了如何将该方法适用于任何移动分析 SDK。
¥This example shows how the approach can be adapted to any mobile analytics SDK.
- Static
- Dynamic
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>
);
}
如果你正在构建一个库,需要将屏幕跟踪集成到 React Navigation 中,你可以将 ref 传递给导航容器,并使用 ready 和 state 事件而不是 onReady 和 onStateChange 属性,以保持逻辑的独立性。
¥If you are building a library that wants to provide screen tracking integration with React Navigation, you can accept a ref to the navigation container and use the ready and state events instead of onReady and onStateChange props to keep your logic self-contained.