javascript - React 的 Google Analytics 设置
问题描述
我已经设法使用ReactGA 库为我的 React 应用程序设置了 Google Analytics,因此当用户四处导航时,它将页面浏览量发送到分析。
问题
我面临的问题是我没有在初始页面加载时向谷歌发送任何分析,因为该history.listen
方法仅在位置更改时触发。
我的设置
在我的项目的根目录中,我初始化了连接:
const history = require("history").createBrowserHistory;
import { Router } from "react-router-dom"
ReactGA.initialize(envConstants.ANALYTICS_TRACKING_ID);
const MyApp = () => (
<Router history={history}>
<MyRoutes />
</Router>
)
因为我只想查看用户在哪些路由上,所以我的路由器中有这个:
const MyRoutes = props => {
props.history.listen(location => {
// won't see this on initial load, but navigating to another route will give me this
console.log("LISTENING")
})
return (...)
}
所以我想知道如何解决这个问题并在用户访问我的网站时发送第一个/初始页面浏览量。我相信我无法用这种history.listen
方法实现这一点。所以,我想我们必须添加一些我不太确定的其他功能。
我很感激我能得到的所有帮助。如果有不清楚的地方,请告诉我。
感谢您的阅读,祝您有美好的一天!
解决方案
问题是在初始页面加载时不会调用历史监听,因为它仅在位置更改时调用。尝试以下内容
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ReactGA from 'react-ga';
const trackPageView = location => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
};
const initGa = history => {
ReactGA.initialize('UA-XXXXXX-X', {
debug: true
});
trackPageView(history.location);
history.listen(trackPageView);
};
const history = createHistory();
initGa(history);
ReactDOM.render((
<Router history={history}>
<Layout />
</Router>
), document.getElementById('root'));
推荐阅读
- c++ - 使用 MSVC 提升迭代器范围并过滤迭代器异常
- java - 正则表达式:带括号的单词(出入)
- java - 为我的 DTO 构建复合唯一约束
- wpf - WPF/ MVVM:文本框的值未使用选定的文件路径更新,但如果转到下一页并返回,则显示该值
- html - 可拖动的 jquery ui 触摸防止专注于 Chrome 上的输入
- java - JavaFX:你如何调用和传递控制对象?
- spacy - 如何在 AWS Glue 中安装 PyCaret
- java - 使用带有 PostgreSQLRangeType 等类型的休眠环境。有可能吗?有没有不重构遗留代码的简单方法?
- python - IndexError:尝试将数据插入到 sqlite3 数据库时,位置参数元组的替换索引 2 超出范围
- python - 如何在乌龟的文本组中使用不同的颜色