メインコンテンツにスキップする
バージョン: 6.x

アナリティクス用の画面トラッキング

現在アクティブになっている画面を追跡するには

  1. コールバックを追加して、状態の変化が通知されるようにする
  2. ルートナビゲーターの状態を取得して、アクティブなルート名を取得する

状態の変化が通知されるようにするには、NavigationContaineronStateChangeプロップを使用します。ルートナビゲーターの状態を取得するには、コンテナーの参照で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>
);
};