1

我通过以下方式使用 React Router 设置了 React-ga:

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

ReactGA.initialize('MY TRACKING CODE', {
  debug: true
});

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


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

如果我已经在页面上并访问另一条路径,我会在控制台上看到以下内容:

 log.js:2 [react-ga] called ga('set', fieldsObject);
 log.js:2 [react-ga] with fieldsObject: {"page":"/products"}
 log.js:2 [react-ga] called ga('send', 'pageview', path);
 log.js:2 [react-ga] with path: /products

但是,如果我第一次访问该页面(通过单击链接或直接在浏览器上输入路径),我在控制台上什么也得不到。

为了计算第一次访问,我是否缺少任何步骤?

4

1 回答 1

4

对于任何有同样问题的人,问题是在初始页面加载时不会调用历史监听,因为它仅在位置更改时调用。

以下设置对我有用:

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

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

const initGa = history => {
  ReactGA.initialize('MY TRACKING CODE', {
    debug: true
  });
  trackPageView(history.location);
  history.listen(trackPageView);
};

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

ReactDOM.render((
  <Provider store={store}>
    <Router history={history}>
      <Layout />
    </Router>
 </Provider>
), document.getElementById('root'));
registerServiceWorker(); 
于 2018-03-03T14:15:01.530 回答