将React路由器页面视图发送到Firebase Analytics

k4aesqcs  于 2023-04-13  发布在  React
关注(0)|答案(3)|浏览(93)

我的应用程序使用React Router的BrowserRouter。我如何跟踪页面浏览量并将其发送到Google Firebase Analytics(我已经安装了firebase-analytics.js)。

46qrfjad

46qrfjad1#

只需在<BrowserRouter>中的任意位置呈现以下组件:

import { useLocation } from "react-router-dom";
import { useEffect } from "react";

function FirebaseAnalytics() {
    const location = useLocation();
    useEffect(() => {
        const analytics = window.firebase && window.firebase.analytics;
        if (typeof analytics === "function") {
            const page_path = location.pathname + location.search;
            analytics().setCurrentScreen(page_path);
            analytics().logEvent("page_view", { page_path });
        }
    }, [location]);
    return null;
}
64jmpszr

64jmpszr2#

作为对Tzach答案的替代/附加考虑,您可能更喜欢导入firebase并设置

const analytics = firebase.analytics;
9gm1akwq

9gm1akwq3#

如果你使用React + TypeScript,会出现一些类型错误。另外,在我看来,最好使用React Hook,因为在这种情况下,你是在向一个组件(而不是另一个组件)添加逻辑。我在下面留下我的建议:

import { useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import { getAnalytics, logEvent } from '@firebase/analytics';

export function useFirebaseRoutesAnalytics() {
    const location = useLocation();

    useEffect(() => {
        const analytics = getAnalytics();
        logEvent(analytics, 'screen_view', {
            firebase_screen: location.pathname, // <- In my case I do not want to include search params, so 'location.pathname' is just what I want
            firebase_screen_class: 'firebase-routes-analytics', // <- This name is up to you
        });
    }, [location]);

    return null;
}

相关问题