简体   繁体   English

必须先调用 ReactGA.initialize

[英]ReactGA.initialize must be called first

I am getting the following warning multiple times (for multiple pages) despite me initializing at the root of my app.尽管我在应用程序的根目录下进行了初始化,但我多次收到以下警告(针对多个页面)。 This makes me wonder if google analytics is even working properly?这让我想知道谷歌分析是否正常工作? [react-ga] ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually

I am using ReactGA to handle my google analytics tags, and I cannot get it to work.我正在使用 ReactGA 来处理我的谷歌分析标签,但我无法让它工作。 According to the documentation and a handful of other questions about this online, all I need to do is insert this at my application root:根据文档和其他一些在线问题,我需要做的就是将它插入到我的应用程序根目录中:

App.js:应用程序.js:

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

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

I am using Server Side Rendering, so I am making sure the window object exists before tracking.我正在使用服务器端渲染,所以我在跟踪之前确保窗口对象存在。 This line is put at the end of my imports on each of my pages:这一行放在我的每个页面上导入的末尾:

example page.js:示例页面.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;

At this point, there isn't a lot of information on how to set up Google Analytics for SSR applications, so I'm not entirely sure what I need to do to get this working.在这一点上,关于如何为 SSR 应用程序设置 Google Analytics 的信息并不多,所以我不完全确定我需要做什么才能使其工作。 Any help is appreciated!任何帮助表示赞赏!

I finally found the solution after a lot of tinkering with potential solutions.在对潜在解决方案进行了大量修补后,我终于找到了解决方案。 Since pageview was being fired before initialize could finish, I tired delaying pageview as much as I could by placing it in componentDidMount() .由于 pageview 在 initialize 完成之前被触发,我厌倦了尽可能多地延迟 pageview 将它放在componentDidMount() That implementation looks like this:该实现如下所示:

App.js:应用程序.js:

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

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

Page.js:页面.js:

import ReactGA from 'react-ga';

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM