reactjs - Google Analytics/React GA:History 对象随着每次位置变化发送越来越多的点击
问题描述
通过监听历史对象的位置变化,我遵循了使用 React-GA 和 React Router 的看似相当样板的说明。这是片段:
if (process.env.NODE_ENV === 'production') {
history.listen(location => {
if (location.pathname.includes('/app')) {
ReactGA.set({ page: location.pathname }, ['appTracker']); // Update the user's current page
ReactGA.pageview(location.pathname, ['appTracker']); // Record a pageview for the given page
} else {
ReactGA.set({ page: location.pathname }, ['marketingTracker']); // Update the user's current page
ReactGA.pageview(location.pathname, ['marketingTracker']); // Record a pageview for the given page
}
});
}
问题是每次位置更改时,它都会发送越来越多的点击。因此,如果我从 /login 开始,它将发送 1 个命中。然后我更改为 /signup,它会在 /signup 上发送 2 次点击。然后我返回登录,它向 /login 发送了 3 次点击。等等。这似乎可能是 BrowserRouter 传递的历史对象的问题,因为控制台日志也会发生同样的事情。就像我提到的那样,上面的片段几乎是从其他几个博客中逐字复制/粘贴的,这些博客引用了 React GA 和 React Router 的标准设置,所以我不确定如何防止它发送这些重复的命中。
解决方案
useLocation()
使用React Router 5.1^ 中的钩子找到了更好的方法:
应用程序.js:
let location = useLocation();
useEffect(() => {
if (process.env.NODE_ENV === 'production') {
if (location.pathname.includes('/app')) {
ReactGA.set({ page: location.pathname }, ['appTracker']); // Update the user's current page
ReactGA.pageview(location.pathname, ['appTracker']); // Record a pageview for the given page
} else {
ReactGA.set({ page: location.pathname }, ['marketingTracker']); // Update the user's current page
ReactGA.pageview(location.pathname, ['marketingTracker']); // Record a pageview for the given page
}
}
}, [location]);
推荐阅读
- ios - collectionView didSlectRow 错误
- python - 将手动创建的 DOK 转换为 CSR
- selenium - 从所需功能创建会话时出错
- google-app-engine - 在谷歌应用引擎端点上部署反应快速应用程序,当我请求 url 时给出错误消息?
- c# - 使用测试数据库进行存储过程测试或将所有内容包装在事务中
- reactjs - SSR SCSS 的 Webpack 配置
- html - 为什么 bootstrap col 不自动占用 12 列?
- html - 多个单选按钮不起作用,只有第一个
- elasticsearch - 如果在 [basic] 许可证上启用了安全性,则必须启用传输 SSL
- visual-studio-code - 在 VS 代码上使用 sage 时如何获得 python 配色方案?