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

Tza*_*ach 2 firebase react-router firebase-analytics

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

Tza*_*ach 5

只需在您的 内的任何位置渲染以下组件<BrowserRouter>


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

function FirebaseAnalytics() {
    let 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;
}
Run Code Online (Sandbox Code Playgroud)