繁体   English   中英

Next.js 谷歌分析与 ReactGA

[英]Next.js Google Analytics with ReactGA

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

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

订阅Router events并使用 GA pageview界面。

请记住使用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} />
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM