在我的 react
应用程序中,我有一些页面:
- 主要
- 服务
- 联系方式
- 个人资料(私有(private))
- 等等..
我需要使用 Google Analytics 跟踪用户事件。我用谷歌搜索react-ga没关系。但有了这个库,我必须在我使用的每条路线上初始化我的 GA。例如:
路线“/” - 主页:
class Main extends Component {
componentDidMount() {
initGA();
}
render() {
return (
<div>
<Component1 />
<Component2 />
</div>
)
}
}
我的 initGA()
看起来像:
import ReactGA from 'react-ga';
export const initGA = () => {
ReactGA.initialize('UA-00000000-1');
ReactGA.pageview(window.location.pathname + window.location.search);
console.log(window.location.pathname + window.location.search);
}
我的应用程序类
看起来像:
class App extends Component {
render() {
return (
<BrowserRouter>
<div className="App">
<Switch>
<Route exact path="/" component={Main} />
<Route exact path="/signup" component={SignupLayout} />
<Route component={PublicLayout} />
</Switch>
</div>
</BrowserRouter>
);
}
}
在我使用react-ga
的方式中,我在每个在路由响应上呈现的组件上添加initGA()
函数。我认为在每个组件中重复 initGA()
是不对的。请问各位,你们如何使用react-ga
?使用react-ga的正确方法是什么?
最佳答案
这就是用钩子(Hook)实现的方法。
App.js
import React, { useEffect } from 'react'
import { Router, Route } from 'react-router-dom'
import { createBrowserHistory } from 'history'
import ReactGA from 'react-ga'
ReactGA.initialize(process.env.REACT_APP_GA_TRACKING_NO)
const browserHistory = createBrowserHistory()
browserHistory.listen((location, action) => {
ReactGA.pageview(location.pathname + location.search)
})
const App = () => {
useEffect(() => {
ReactGA.pageview(window.location.pathname + window.location.search)
}, [])
return <div>Test</div>
}
上面使用类组件的答案几乎没问题,但您不会在分析中看到第一页加载。 history.listen
仅在路线更改时才会触发。当您第一次加载页面时,不会发生这种情况。为了解决这个问题,我在 App
组件中添加了一个 useEffect
钩子(Hook)。如果用户重新加载网站,App
将始终重新呈现。 ReactGA.pageview(window.location.pathname + window.location.search)
确保如果路线不是 '/'
的话,我们会将重新加载归因于正确的路线>.
关于javascript - 如何将 Google Analytics 与 React 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52724447/