首页 > 解决方案 > React 的 Google Analytics 设置

问题描述

我已经设法使用ReactGA 库为我的 React 应用程序设置了 Google Analytics,因此当用户四处导航时,它将页面浏览量发送到分析。

问题

我面临的问题是我没有在初始页面加载时向谷歌发送任何分析,因为该history.listen方法仅在位置更改时触发。

我的设置

在我的项目的根目录中,我初始化了连接:

const history = require("history").createBrowserHistory;
import { Router } from "react-router-dom"

ReactGA.initialize(envConstants.ANALYTICS_TRACKING_ID);

const MyApp = () => (
  <Router history={history}>
    <MyRoutes /> 
  </Router>
)

因为我只想查看用户在哪些路由上,所以我的路由器中有这个:

const MyRoutes = props => {
  props.history.listen(location => {
    // won't see this on initial load, but navigating to another route will give me this
    console.log("LISTENING") 
  })

  return (...)
}

所以我想知道如何解决这个问题并在用户访问我的网站时发送第一个/初始页面浏览量。我相信我无法用这种history.listen方法实现这一点。所以,我想我们必须添加一些我不太确定的其他功能。

我很感激我能得到的所有帮助。如果有不清楚的地方,请告诉我。

感谢您的阅读,祝您有美好的一天!

标签: javascriptreactjsreact-routerreact-router-domreact-ga

解决方案


问题是在初始页面加载时不会调用历史监听,因为它仅在位置更改时调用。尝试以下内容

import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ReactGA from 'react-ga';

const trackPageView = location => {
  ReactGA.set({ page: location.pathname });
  ReactGA.pageview(location.pathname);
};

const initGa = history => {
  ReactGA.initialize('UA-XXXXXX-X', {
    debug: true
  });
  trackPageView(history.location);
  history.listen(trackPageView);
};

const history = createHistory();
initGa(history);

ReactDOM.render((
  <Router history={history}>
      <Layout />
    </Router>
), document.getElementById('root'));

推荐阅读