分析的畫面追蹤
如要追蹤當前啟用的畫面,我們需要
- 加入一個回呼函式以接收狀態變更通知
- 取得根導覽器狀態並找出啟用的路線名稱
如要接收狀態變更通知,我們可以使用 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>
);
};