首页 > 解决方案 > 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 的标准设置,所以我不确定如何防止它发送这些重复的命中。

标签: reactjsgoogle-analyticsreact-routerreact-ga

解决方案


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]);

推荐阅读