必须先调用 ReactGA.initialize

Mat*_*rom 10 javascript google-analytics reactjs server-side-rendering react-ga

尽管我在应用程序的根目录下进行了初始化,但我多次收到以下警告(针对多个页面)。这让我想知道谷歌分析是否正常工作? [react-ga] ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually

我正在使用 ReactGA 来处理我的谷歌分析标签,但我无法让它工作。根据文档和其他一些在线问题,我需要做的就是将它插入到我的应用程序根目录中:

应用程序.js:

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

const app = () => (
    // Root level components here, like routing and navigation
)
Run Code Online (Sandbox Code Playgroud)

我正在使用服务器端渲染,所以我在跟踪之前确保窗口对象存在。这一行放在我的每个页面上导入的末尾:

示例页面.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;
Run Code Online (Sandbox Code Playgroud)

在这一点上,关于如何为 SSR 应用程序设置 Google Analytics 的信息并不多,所以我不完全确定我需要做什么才能使其工作。任何帮助表示赞赏!

Mat*_*rom 5

在对潜在解决方案进行了大量修补后,我终于找到了解决方案。由于网页浏览在初始化完成之前被触发,我厌倦了尽可能多地将网页浏览放在componentDidMount(). 该实现如下所示:

应用程序.js:

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

const App = () => (
  <div className="App">
    <Navigation />
            
    <AppRouting />
  </div>
);
Run Code Online (Sandbox Code Playgroud)

页面.js:

import ReactGA from 'react-ga';

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

    render() {
        return(
            <Component />
        );
    }
}
Run Code Online (Sandbox Code Playgroud)