React Router BrowserRouter 历史推送和 Google 分析

React Router BrowserRouter History Push & Google Analytics

我有一个轮播组件,我想更改 URL 以便 google 分析可以查看用户执行了哪些步骤(无需重新加载页面)。

我使用 React Router 及其 BrowserRouter 组件在 this.props.history.push(`#${value}`);withRouter 的帮助下更新路由,成功更新了 URL 路由。但是 Google Analytics 似乎看不出有什么区别...网站位于 link 如果您想检查行为: http://upscale-technology.com

通常,您的 Google 分析详细信息会添加到 HTML 文件中,在加载文件时会触发页面查看。当您访问同一网站的另一个页面并且 Google Analytics 在那里实施时,它将记录新页面。

在单页应用程序中,路由在客户端处理,无需重新加载页面。您正在寻找的是一种让 Google Analytics 知道它应该在执行特定操作时记录页面视图的方法。它可能是单击事件、状态更改或路由更改。由你决定。

为此,您可以使用 React-GA 库。按照以下方式使用。

// Import it at the top of the file
import ReactGA from 'react-ga';

// Initialize it once, e.g. in your componentDidMount for example.
ReactGA.initialize('UA-000000-01');

// Whenever you want to log anything to Google Analytics, use the below. 
ReactGA.pageview('/carousel/#1');

注意:
在实现 .pageview([url]) 函数的地方要小心。如果您不小心,它可能会在重新渲染时触发。这意味着您的指标会出现错误的页面浏览量,从而影响您的分析。