首先需要调用ReactGA.initialize。

16

尽管我在应用程序的根部初始化,但我仍多次收到以下警告(对于多个页面)。这让我怀疑Google Analytics是否正常工作?

[react-ga] ReactGA.initialize必须首先被调用或GoogleAnalytics必须手动加载

我正在使用ReactGA来处理我的Google Analytics标签,但无法使其正常工作。根据文档和在线上的一些其他问题,我只需要在我的应用程序根部插入以下内容:

App.js:

import ReactGA from 'react-ga';
ReactGA.initialize('G-xxxxxxxxxx');

const app = () => (
    // Root level components here, like routing and navigation
)

我正在使用服务器端渲染,因此在跟踪之前要确保窗口对象存在。这行代码放置在每个页面的导入结束处:

示例 page.js:

import ReactGA from 'react-ga';
if (typeof(window) !== 'undefined') {
    ReactGA.pageview(window.location.pathname + window.location.search);
}

function page() {
    return(<div className="page">Hello, World</div>)
}

export default page;

目前关于如何为SSR应用程序设置Google Analytics的信息很少,因此我不确定需要做什么才能使其正常工作。 感谢任何帮助!

2个回答

7

经过尝试了很多潜在的解决方案,我终于找到了解决方法。由于initialize还没有完成就会触发pageview,因此我尝试将其放在componentDidMount()中尽可能地延迟pageview的时间。实现如下:

App.js:

//imports
import ReactGA from 'react-ga';
ReactGA.initialize('UA-xxxxxxxxx-x');

const App = () => (
  <div className="App">
    <Navigation />
            
    <AppRouting />
  </div>
);

Page.js:

import ReactGA from 'react-ga';

class MyPage extends React.Component {
    componentDidMount() {
        ReactGA.pageview(window.location.pathname + window.location.search);
    }

    render() {
        return(
            <Component />
        );
    }
}

0
在函数式组件中,可以使用 useEffect 钩子来实现相同的功能。
useEffect(() => {
 ReactGA.pageview(window.location.pathname + window.location.search);
}, ['your dep'])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接