[英]Trouble implementing gtag in React SPA
我试图在React SPA中实现GTag。
我有以下代码:
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans" />
</head>
<body>
<div id="app"></div>
<% if (process.env.GA_TRACKING_ID) { %>
<script
async
src="https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}"
></script>
<% } %>
</body>
</html>
gtag.jsx
window.dataLayer = window.dataLayer || [];
export default function gtag(...args) {
window.dataLayer.push(args);
}
GTag.jsx
import PropTypes from 'prop-types';
import React from 'react';
import gtag from '../../utils/gtag';
export default class GTag extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
history: PropTypes.shape().isRequired,
};
componentWillMount() {
const { history } = this.props;
history.listen(location => {
console.log(location);
gtag('config', process.env.GA_TRACKING_ID, { page_path: location.pathname });
});
}
render() {
const { children } = this.props;
return children;
}
}
index.jsx (Webpack入口点)
import gtag from './utils/gtag';
// ...
gtag('js', new Date());
gtag('config', process.env.GA_TRACKING_ID);
每当我导航到页面时,都会从console.log
语句将其记录到控制台。 但是,我在分析控制台中没有看到任何活动。
我已经检查了压缩后的代码,并在生产版本中正确替换了GA_TRACKING_ID变量。
我想念什么?
事实证明,应将Arguments
推入dataLayer
而不是数组。 这意味着不支持gtag函数的传播语法。
更新了gtag.jsx :
window.dataLayer = window.dataLayer || [];
export default function gtag() {
// The gtag dataLayer requires an actual Arguments object to be pushed.
// eslint-disable-next-line prefer-rest-params
window.dataLayer.push(arguments);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.