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

标签 javascript reactjs google-optimize

我正在努力使用 Google 优化工具。我需要在我的页面中添加这个标签:

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

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

将调用移动到包含函数的括号中

是否可以重写 Google Optimize 所需的代码以实现 React、linter 友好?

谢谢

最佳答案

我不认为是 React 给了你这个警告,而是你的 linter。

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

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

关于javascript - 如何将 JS 脚本标签添加到 React App 的 ComponentDidMount 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51680094/

相关文章:

reactjs - 我可以给 react 查询一个超时(秒或毫秒......)所以在这段时间之后它会停止网络请求吗?

javascript - reactjs 意外 token '<'

google-analytics - 此页面上未正确安装ID为GTM-…的容器的Google Optimize代码段

google-analytics - 无需 Google Optimize 即可填写 ExperimentID 和 ExperimentVariant

javascript - 使用 Jcrop 调整图像大小

javascript - pjax 失去了 Rails javascript

javascript - 如何使用 LocalStorage 使复选框持久化?

reactjs - 如何更改此 MUI 循环进度的圆圈颜色

reactjs - Google Optimize 无法与 React App 配合使用(未设置 cookie)

javascript - angularjs Controller 功能不起作用