如何使用appDir在NextJS 13项目中实现谷歌分析?

qacovj5a  于 2023-03-18  发布在  其他
关注(0)|答案(1)|浏览(163)
//GoogleAnalytics.tsx

"use client";
import Script from "next/script";

const GoogleAnalytics = ({ GA_TRACKING_ID }: { GA_TRACKING_ID: string }) => {
  return (
    <>
      <Script
        src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
        strategy="afterInteractive"
      />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
        window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', ${GA_TRACKING_ID});
        `}
      </Script>
    </>
  );
};

export default GoogleAnalytics;
//layout.tsx

import GoogleAnalytics from "@/components/molecules/GoogleAnalytics";
import { ReactNode } from "react";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <GoogleAnalytics GA_TRACKING_ID={process.env.GA_TRACKING_ID} />
      <body>      
        {children}
      </body>
    </html>
  );
}

使用这段代码,脚本标记可以正确地填充我的ID G-XXXXXXX. x1c 0d1x
但是,当加载页面时,我在浏览器控制台中得到一个“G未定义”错误。

VM689:6 Uncaught ReferenceError: G is not defined
    at <anonymous>:6:26
    at loadScript (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/next@13.2.4_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/client/script.js:91:19)
    at eval (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/next@13.2.4_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/client/script.js:182:17)
    at commitHookEffectListMount (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/next@13.2.4_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:26416:26)

我已经尝试过将GoogleAnalytics标记放在正文中,也放在head. tsx中。同样的错误。

pobjuy32

pobjuy321#

我发现“G is not defined”代表什么。G实际上是跟踪ID的第一个字母。通过在这里使用模板字符串,我没有意识到最后的代码是错误的。我在这里没有导入字符串,而是从字面上导入跟踪ID,因此将其视为变量。

为了解决这个问题,我简单地加上了引号:

gtag('config', '${GA_TRACKING_ID}');

相关问题