reactjs - 如何让 Google Analytics 与 React 一起工作
问题描述
我正在尝试跟踪每个页面,但每次单击刷新按钮时谷歌只会注册一个视图。当iv'e路由到新路径时不会。有人对如何使这项工作有想法吗?
import React, {useEffect} from 'react';
import { BrowserRouter, Switch, Route } from "react-router-dom";
import OurWork from "./ourWork/ourWork"
import Home from "./home/Home"
import Packages from "./packages/Packages"
import Contacts from "./contact/Contact"
import ReactGA from 'react-ga'
import createHistory from 'history/createBrowserHistory'
const Routes = () => {
const {
ContactPage
} = Contacts();
const history = createHistory()
history.listen(location => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
useEffect(() => {
ReactGA.pageview(window.location.pathname + window.location.search)
}, [history])
return(
<BrowserRouter history={history}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/ourwork" exact component={OurWork} />
<Route path="/packages" exact component={Packages} />
<Route path="/Contact" exact component={ContactPage} />
</Switch>
</BrowserRouter>
)
}
export default Routes;
解决方案
看起来与此处描述的相同问题。尝试更改<BrowserRouter history={history}>
为并从中<Router history={history}>
导入,如下所示:Router
"react-router-dom"
import React, {useEffect} from 'react';
import { Router, Switch, Route } from "react-router-dom";
import OurWork from "./ourWork/ourWork"
import Home from "./home/Home"
import Packages from "./packages/Packages"
import Contacts from "./contact/Contact"
import ReactGA from 'react-ga'
import createHistory from 'history/createBrowserHistory'
const Routes = () => {
const {
ContactPage
} = Contacts();
const history = createHistory()
history.listen(location => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
useEffect(() => {
ReactGA.pageview(window.location.pathname + window.location.search)
}, [history])
return(
<Router history={history}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/ourwork" exact component={OurWork} />
<Route path="/packages" exact component={Packages} />
<Route path="/Contact" exact component={ContactPage} />
</Switch>
</Router>
)
}
export default Routes;
推荐阅读
- python - 计算列表中海龟的步数 - python
- sql-server - 仅当来自选择的单个结果时才从选择更新
- android - 在我的代码中在哪里以及如何开始和停止进度条
- sql-server - STContains - 对多边形内的点进行测试失败
- node.js - 无法在 Node.js 中使用 winston 记录错误
- java - 如何为 TensorFlow Lite 模型指定 Firebase 模型输入以预测 Android 中的项目推荐
- sql - sp_addsrvrolemember 中的转义通配符 *
- c# - dotnet core 3.1 windows 服务无法加载配置设置
- networking - 通过防火墙的 GCP 端口转发
- outlook - 在 Outlook 上单击签名如何获取其内容