アナリティクス用の画面トラッキング
現在アクティブになっている画面を追跡するには
- コールバックを追加して、状態の変化が通知されるようにする
- ルートナビゲーターの状態を取得して、アクティブなルート名を取得する
状態の変化が通知されるようにするには、NavigationContainer
のonStateChange
プロップを使用します。ルートナビゲーターの状態を取得するには、コンテナーの参照でgetRootState
メソッドを使用します。onStateChange
は初期レンダリングでは呼び出されないため、初期画面は別途設定してください。
例
この例は、このアプローチをモバイルアナリティクスSDKに適用する方法を示しています。
import {
NavigationContainer,
useNavigationContainerRef,
} from '@react-navigation/native';
export default () => {
const navigationRef = useNavigationContainerRef();
const routeNameRef = useRef();
return (
<NavigationContainer
ref={navigationRef}
onReady={() => {
routeNameRef.current = navigationRef.getCurrentRoute().name;
}}
onStateChange={async () => {
const previousRouteName = routeNameRef.current;
const currentRouteName = navigationRef.getCurrentRoute().name;
const trackScreenView = () => {
// Your implementation of analytics goes here!
};
if (previousRouteName !== currentRouteName) {
// Save the current route name for later comparison
routeNameRef.current = currentRouteName;
// Replace the line below to add the tracker from a mobile analytics SDK
await trackScreenView(currentRouteName);
}
}}
>
{/* ... */}
</NavigationContainer>
);
};