我试图在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);
}