gpt4 book ai didi

javascript - 如何在 next.js 应用中使用谷歌分析?

转载 作者:行者123 更新时间:2023-12-01 14:55:39 26 4
gpt4 key购买 nike

我将 styled-components 与 next.js 一起使用,因此我的样式需要在服务器端呈现,因此如何将谷歌分析添加到我的网站?

我查了next.js google analytics example但正如我所说,由于使用样式组件,我的 _document 文件有所不同。

// _document.js

import React from 'react'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage

try {
ctx.renderPage = () => originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
})

const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}

export default MyDocument

最佳答案

正确初始化 gtag , 在 _document.js 中执行以下操作或您定义的任何位置Head :

import Document, { Head } from "next/document";

export default class MyDocument extends Document {
render() {
return (
// ...
<Head>
<script
async
src="https://www.googletagmanager.com/gtag/js?id=[Tracking ID]"
/>

<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '[Tracking ID]', { page_path: window.location.pathname });
`,
}}
/>
</Head>
);
}
}
以上将跟踪页面加载时的页面浏览量。要跟踪导航,请将以下内容添加到 _app.js :
import { useRouter } from 'next/router';
import { useEffect } from "react";

export default const App = () => {
const router = useRouter();

const handleRouteChange = (url) => {
window.gtag('config', '[Tracking ID]', {
page_path: url,
});
};

useEffect(() => {
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);

return (
// ...
);
};
也可以看看:
  • https://github.com/vercel/next.js/tree/canary/examples/with-google-analytics
  • https://github.com/vercel/next.js/issues/160
  • 关于javascript - 如何在 next.js 应用中使用谷歌分析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60411351/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com