【问题标题】:Next.js Google Analytics with ReactGANext.js 谷歌分析与 ReactGA
【发布时间】:2023-01-14 11:45:21
【问题描述】:

您好,我正在使用 ReactGA4 在 Next 应用程序中跟踪我的分析。我面临的问题是,在用户重新加载页面之前,我无法看到用户所在的路径。这是我的代码。

ReactGA.initialize("UA-xxxxxxx");
ReactGA.send("pageview");

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    订阅Routerevents,使用GApageview接口。

    请记住使用routeChangeComplete,它将通过 ReactGA 方法发送页面视图

    修改nextjs例子

    import { useEffect } from "react";
    import { useRouter } from "next/router";
    
    export default function MyApp({ Component, pageProps }) {
      const router = useRouter();
    
      useEffect(() => {
        const handleRouteChange = (url, { shallow }) => {
          // REACTGA
          // Send pageview with a custom path
          ReactGA.send({ hitType: "pageview", page: "/my-path" });
          console.log(`App is changing to ${url} ${shallow ? "with" : "without"} shallow routing`);
        };
    
        router.events.on("routeChangeComplete", handleRouteChange);
    
        // If the component is unmounted, unsubscribe
        // from the event with the `off` method:
        return () => {
          router.events.off("routeChangeComplete", handleRouteChange);
        };
      }, []);
    
      return <Component {...pageProps} />;
    }
    

    【讨论】:

    • 所以我把 ReactGA.initialize("UA-xxxxxxx") 放在 ReactGA.send({ hitType: "pageview", page: "/my-path" })... 之前?提前致谢。我也在使用 React cookies 同意,所以代码有点乱
    • Yes, initialize before - 路由器代码订阅了软导航。
    • 非常感谢它就像魅力一样!
    • 乐于助人,欢迎来到 Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受!
    • 关于让useEffect 没有部门的任何想法?如果router.events改变了,它永远不会更新?
    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2016-05-11
    相关资源
    最近更新 更多