在React应用程序中将Google Analytics分析与到达路由器集成

问题描述

我想将Google Analytics(分析)集成到我的React应用程序中。我正在使用到达路由器,这会使事情变得更复杂。

如果我使用这样的位置提供程序,则导航API无效。因此,如果单击任何页面,则页面不会呈现

import { Router,createHistory,LocationProvider }from "@reach/router";
import ReactGA from "react-ga";
ReactGA.initialize("G-xxxxxxx");
const history= createHistory(window);
history.listen( window => {
  ReactGA.pageview(window.location.pathname+ window.location.search);
  console.log('page=>',window.location.pathname);
});
<LocationProvider history={history}>
  <Router></Router>
</LocationProvider>

如果我使用globalHistory,则Google Analytics(分析)仅在首页上可用,而没有其他页面统计

ReactGA.initialize("G-XXXXXXXXXXX");
globalHistory.listen(({ location }) => {
  window.ga('send','pageview');
  // or use the new gtag API
  window.gtag('config','G-XXXXXXXXXX',{'page_path': location.pathname});
});

任何人都知道如何以第一或第二种方式解决此问题吗?

解决方法

这取决于您使用的是Google Analytics(分析)4属性ID(G-XXXXXXXX),而有问题的React Analytics软件包适用于Universal Analytics。建议您创建一个Universal Analytics属性(如下图所示),并使用相对标识符UA-XXXXXXX-X:

enter image description here