【问题标题】:Google Analytics setup for ReactReact 的 Google Analytics 设置
【发布时间】:2019-12-06 11:07:26
【问题描述】:

我已经设法使用ReactGA library 为我的 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 方法实现这一点。所以,我想我们必须添加一些我不太确定的其他功能。

感谢您在这方面获得的所有帮助。如果有不清楚的地方,请告诉我。

感谢您的阅读,祝您有愉快的一天!

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom react-ga


    【解决方案1】:

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

    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'));
    

    【讨论】:

      猜你喜欢
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多