如何为 React-Router 设置 Google Analytics?

新手上路,请多包涵

我正在尝试在我的反应站点上设置 Google Analytics,并且遇到了一些包,但没有一个包具有我在示例方面的设置。希望有人可以对此有所了解。

我正在查看的包是 react-ga

我的 index.js 上的渲染方法看起来像这样。

 React.render((
<Router history={createBrowserHistory()}>
    <Route path="/" component={App}>
        <IndexRoute component={Home} onLeave={closeHeader}/>
        <Route path="/about" component={About} onLeave={closeHeader}/>
        <Route path="/gallery" component={Gallery} onLeave={closeHeader}/>
        <Route path="/contact-us" component={Contact} onLeave={closeHeader}>
            <Route path="/contact-us/:service" component={Contact} onLeave={closeHeader}/>
        </Route>
        <Route path="/privacy-policy" component={PrivacyPolicy} onLeave={closeHeader} />
        <Route path="/feedback" component={Feedback} onLeave={closeHeader} />
    </Route>
    <Route path="*" component={NoMatch} onLeave={closeHeader}/>
</Router>), document.getElementById('root'));

原文由 John Fu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 883
2 个回答

保留对历史对象的引用。 IE

 import { createBrowserHistory } from 'history';

var history = createBrowserHistory();

ReactDOM.render((
    <Router history={history}>
        [...]

然后添加一个监听器来记录每个页面浏览量。 (这假设您已经以通常的方式设置了 window.ga 对象。)

 history.listen((location) => {
    window.ga('set', 'page', location.pathname + location.search);
    window.ga('send', 'pageview');
});

原文由 David L. Walsh 发布,翻译遵循 CC BY-SA 4.0 许可协议

问题是关于 react-ga 但这个包很快就会过时,因为它 不支持 Google Analytics 4。下面是一个适用于任何库或本机的通用解决方案 gtag 。要将 GA4 添加到 React,请查看此答案: https ://stackoverflow.com/a/73354959/2771889。

由于 react-router v5.1.0 使用 useLocation 可以更容易地解决这个问题。

usePageTracking.js

 import { useEffect} from "react";
import { useLocation } from "react-router-dom";

const usePageTracking = () => {
  const location = useLocation();

  useEffect(() => {
    // track pageview with gtag / react-ga / react-ga4, for example:
    window.gtag("event", "page_view", {
      page_path: location.pathname + location.search,
    });
  }, [location]);
};

export default usePageTracking;

App.js

 const App = () => {
  usePageTracking();

  return (...);
};

请记住,Google Analytics 会自动跟踪页面,但这并不适用于所有用例。例如, hashsearch 不跟踪 参数更改。这会导致很多混乱。例如,当使用 HashRouter 或锚链接时,将不会跟踪导航。要完全控制页面浏览跟踪,您可以 禁用自动跟踪。有关详细说明,请参阅: The Ultimate Guide to Google Analytics (UA & GA4) on React (Or Anything Else)

您可以在我将它与 GA4 一起使用的 cra-typescript-starter 中看到它的工作原理。

原文由 thisismydesign 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进