我正在尝试在 SPA React-app 中实现 Google Analytics 来记录事件。
我在 Google Analytics 中创建了一个数据流并获得了一个测量 ID。然后我做了一个自定义钩子:
import ReactGA from 'react-ga'
type GoogleAnalyticsReturn = {
regEventGA: (
category: string,
action: string,
value?: number,
label?: string,
) => void
initializeGa: (pageUrl: string) => void
}
const ga_measurement_id = 'INSERT CODE HERE'
const ga_debug = true
export const useGoogleAnalytics = (): GoogleAnalyticsReturn => {
const initializeGa = (pageUrl: string) => {
if (ga_measurement_id) {
ReactGA.initialize(ga_measurement_id, {
debug: ga_debug,
})
ReactGA.set({ anonymizeIp: true })
ReactGA.pageview(pageUrl)
}
}
const regEventGA = (
category: string,
action: string,
value?: number,
label?: string,
) => {
ReactGA.event({
category: category,
action: action,
value: value,
label: label,
})
}
return { regEventGA, initializeGa }
}
然后我使用钩子在 App.tsx 中初始化 GA:
import React from 'react'
import { useGoogleAnalytics } from './utils/useGoogleAnalytics/useGoogleAnalytics'
function App(): JSX.Element {
const { initializeGa } = useGoogleAnalytics()
initializeGa(window.location.pathname)
return (
<MyComponent />
)
}
export default App
在 MyComponent 中,发送了一个事件:
import React from 'react'
import { useGoogleAnalytics } from './utils/useGoogleAnalytics/useGoogleAnalytics'
export const MyComponent = (): JSX.Element => {
const { regEventGA } = useGoogleAnalytics()
const handleClick = () => {
regEventGA('My Component', 'Button click')
}
return (
<button onClick={handleClick}>
Click me!
</button>
)
}
当我单击按钮时,控制台正在打印:
[react-ga] called ga('send', fieldObject)
[react-ga] with fieldObject {"hitType":"event","eventCategory":"My Component","eventAction":"Button click"}
[react-ga] with trackers: undefined
但谷歌分析上没有出现任何内容。