代码之家  ›  专栏  ›  技术社区  ›  AnnaSm

如何将JS脚本标记从添加到React应用程序的ComponentDidMount中?

  •  1
  • AnnaSm  · 技术社区  · 8 年前

    我正在使用谷歌优化。我需要在页面中添加此标记:

    <script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
    h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
    (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
    })(window,document.documentElement,'async-hide','dataLayer',4000,
    {'GTM-X':true});</script>
    

    为了让这起反应起作用,我正在尝试以下操作:

    import React from 'react';
    
    const MarketingPage = class extends React.Component {
      compomentDidMount = () => {
        (function(a, s, y, n, c, h, i, d, e) {
          s.className+=' '+y;
          h.start=1*new Date;
          h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
          (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
          })(window,document.documentElement,'async-hide','dataLayer',4000,
          {'GTM-X':true}
        );
      }
    

    React不喜欢这个。。我得到以下错误:

    Move the invocation into the parens that contain the function

    是否可以重写Google Optimize所需的代码,使其对linter更友好?

    谢谢

    1 回复  |  直到 8 年前
        1
  •  3
  •   Tholle    8 年前

    我认为这不是给你警告的反应,而是你的皮棉。

    你可以把你的函数放在一个变量中,然后调用它。

    const MarketingPage = class extends React.Component {
      compomentDidMount() {
        const analytics = function(a, s, y, n, c, h, i, d, e) {
          s.className+=' '+y;
          h.start=1*new Date;
          h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
          (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
        };
    
        analytics(window,document.documentElement,'async-hide','dataLayer',4000,{'GTM-X':true});
      }
    }