首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React-ga不计算首次访问

React-ga不计算首次访问
EN

Stack Overflow用户
提问于 2018-02-27 00:13:34
回答 1查看 574关注 0票数 1

我已经用React Router以以下方式设置了React-ga:

代码语言:javascript
复制
...
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();

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

代码语言:javascript
复制
 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

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

为了计算第一次访问,我是否遗漏了什么步骤?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-03 22:15:02

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

以下设置适用于我:

代码语言:javascript
复制
...
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(); 
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48992599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档