问题描述
我正在尝试向Gatbsy GTM插件添加自定义数据层代码段(dataLayer.push(❴'event':“ pageview”❵))。我该怎么做?有任何帮助吗?
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ originalLocation: document.location.protocol + '//' + document.location.hostname + document.location.pathname + document.location.search });
解决方法
在组件/页面中使用useEffect
钩子。 useEffect
是在加载DOM树后触发的事件(类似于componentDidMount
,componentDidUpdate
和componentWillUnmount
生命周期的组合)。
import React,{ useState,useEffect } from 'react';
function Example() {
const [count,setCount] = useState(0);
useEffect(() => {
if (typeof window !== 'undefined'){
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ originalLocation: document.location.protocol + '//' + document.location.hostname + document.location.pathname + document.location.search });
}
},[]);
return (
<div>
<p>Your page</p>
</div>
);
}
请注意typeof window !== 'undefined'
条件,这是dealing with global objects (such as window
or document
)在服务器端呈现中的推荐语句。