1

请让我知道如何在其中包含谷歌分析preact?我发现有人做了react如下

  componentDidMount() {
    window.ga = window.ga || function() { (ga.q = ga.q || []).push(arguments)  }; ga.l = +new Date;
    const account = this.props.account;
    // const scriptProtocol = ("https:" === document.location.protocol ? "https://ssl" : "http://www");
    const scriptSrc = `//google-analytics.com/analytics.js`;
    jQuery.getScript(scriptSrc, () => {
      // Track Route changes
      ga("create", account, "auto");
      if(this.props.history) {
        this.props.history.listen((newLocation) => {
          ga("send", "pageview", newLocation.pathname);
        });
      }
    });
  }

但问题是jQuery上面代码中使用的这个人undefined。请让我知道如何解决它。

4

2 回答 2

1

您可以使用react-ga依赖项来实现这一点。

如该项目的文档中所述:将其添加为依赖项npm install react-ga --save (例如,如果您使用的是 npm),然后只需将此代码添加到您的主要组件中:

import ReactGA from 'react-ga';
ReactGA.initialize('UA-000000-01');
ReactGA.pageview(window.location.pathname + window.location.search);

react-ga也有函数调用来做同样的事情,你会用你的 jQuery 方法做同样的事情,比如将页面浏览量和其他数据发送到谷歌分析。

于 2018-07-17T22:06:21.460 回答
0

要使用 jquery,请遵循此

尝试安装npm install jquery

然后导入jquery如下

import jQuery from 'jquery';

添加谷歌分析的其他方法是添加以下不需要jquery的代码

 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', '***YOUR ID HERE****', 'auto');
  ga('send', 'pageview');
于 2017-11-23T01:06:29.197 回答