如何使用到达路由器和 google 分析来跟踪页面浏览量?

How to track page views in react using reach router and google analytics?

我正在将 backbone 应用程序移植到 React 应用程序。在 backbone 应用程序中,我有以下代码段

    <!-- Begin UA code -->
    <script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-xxx', 'auto');

    // Load plugins

    // Rewrite all GA pages with /ra_minisite prefix
    ga('require', 'cleanUrlTracker', {
      stripQuery: true,
      queryDimensionIndex: 1,
      urlFieldsFilter: function(fieldsObj, parseUrl) {
        fieldsObj.page = '/ra_minisite'+parseUrl(fieldsObj.page).pathname
        return fieldsObj;
      },
    });

    ga('require', 'eventTracker');
    ga('require', 'maxScrollTracker');

    // Customize so WS.com not tracked as outbound link
    ga('require', 'outboundLinkTracker');

    ga('require', 'socialWidgetTracker');
    ga('require', 'urlChangeTracker');

    // Commented out so we can call after all API calls are done
    // Called from metaManager
    // ga('send', 'pageview');

    </script>
    <script async src="https://www.google-analytics.com/analytics.js"></script>
    <script async src="/autotrack.js"></script>
    <!-- end UA code -->

然后在更新元标记后在每个页面上呈现它调用

window.ga('send', 'pageview');

我假设我可以将初始化逻辑放到 index.html 中,但是将 window.ga('send', 'pageview'); 挂接到 reach router 的一种简单好方法是什么,这样当路由更改或更新时,pageview 会被发送到 GA?

您可以手动创建可以使用 createHistory 函数侦听更改的历史对象。您可以附加一个侦听器并在那里发送一个 pageview 事件。

例子

import { createHistory, LocationProvider } from '@reach/router';

const history = createHistory(window);

history.listen(() => {
  window.ga('send', 'pageview');
});

const App = () => (
  <LocationProvider history={history}>
    <Routes />
  </LocationProvider>
);

您可以收听全局历史对象。在你的 App.js:

import { globalHistory } from '@reach/router';

globalHistory.listen(({ location }) => {
  window.ga('send', 'pageview');
  // or use the new gtag API
  window.gtag('config', 'GA_MEASUREMENT_ID', {'page_path': location.pathname});
});

这是最简单的方法,代码量最少,而且与最佳答案中的 LocationProvider 方法不同,它不会破坏全局 navigate API.

不幸的是,globalHistory 似乎没有任何记录,因此很难找到。

您可以使用来自到达路由器的位置提供商API:

import { Router,createHistory,LocationProvider }from "@reach/router";
import ReactGA from "react-ga";
ReactGA.initialize("UA-103xxxxx-xx");
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>

Here 是完整的解决方案。