如何将JS脚本标签从中添加到React App的ComponentDidMount中?

时间:2018-08-03 21:09:27

标签: javascript reactjs google-optimize

我正在使用Google Optimize。我需要在页面内添加此标签:

<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>

为了使它在React中工作,我正在尝试以下方法:

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

反应不喜欢这个。。我收到以下错误:

Move the invocation into the parens that contain the function

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

谢谢

1 个答案:

答案 0 :(得分:3)

我不认为这是React给您的警告,而是您的小孩子。

您可以将函数放在变量中,然后立即调用它。

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