javascript - 如何将 Google Analytics 与 React 结合使用?

标签 javascript reactjs google-analytics react-ga

在我的 react 应用程序中,我有一些页面:

  1. 主要
  2. 服务
  3. 联系方式
  4. 个人资料(私有(private))
  5. 等等..

我需要使用 Google Analytics 跟踪用户事件。我用谷歌搜索react-ga没关系。但有了这个库,我必须在我使用的每条路线上初始化我的 GA。例如:

路线“/” - 主页:

class Main extends Component {

    componentDidMount() {
        initGA();
    }

    render() {
        return (
            <div>
                <Component1 />
                <Component2 />
            </div>
        )
    }
}

我的 initGA() 看起来像:

import ReactGA from 'react-ga';

export const initGA = () => {
    ReactGA.initialize('UA-00000000-1');
    ReactGA.pageview(window.location.pathname + window.location.search);
    console.log(window.location.pathname + window.location.search);
}

我的应用程序类看起来像:

class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <div className="App">

                    <Switch>
                        <Route exact path="/" component={Main} />
                        <Route exact path="/signup" component={SignupLayout} />
                        <Route component={PublicLayout} />
                    </Switch>

                </div>
            </BrowserRouter>
        );
    }
}

在我使用react-ga的方式中,我在每个在路由响应上呈现的组件上添加initGA()函数。我认为在每个组件中重复 initGA() 是不对的。请问各位,你们如何使用react-ga?使用react-ga的正确方法是什么?

最佳答案

这就是用钩子(Hook)实现的方法。

App.js

import React, { useEffect } from 'react'
import { Router, Route } from 'react-router-dom'
import { createBrowserHistory } from 'history'
import ReactGA from 'react-ga'

ReactGA.initialize(process.env.REACT_APP_GA_TRACKING_NO)
const browserHistory = createBrowserHistory()
browserHistory.listen((location, action) => {
  ReactGA.pageview(location.pathname + location.search)
})

const App = () => {
  useEffect(() => {
    ReactGA.pageview(window.location.pathname + window.location.search)
  }, [])

  return <div>Test</div>
}

上面使用类组件的答案几乎没问题,但您不会在分析中看到第一页加载。 history.listen 仅在路线更改时才会触发。当您第一次加载页面时,不会发生这种情况。为了解决这个问题,我在 App 组件中添加了一个 useEffect 钩子(Hook)。如果用户重新加载网站,App 将始终重新呈现。 ReactGA.pageview(window.location.pathname + window.location.search) 确保如果路线不是 '/' 的话,我们会将重新加载归因于正确的路线>.

关于javascript - 如何将 Google Analytics 与 React 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52724447/

相关文章:

google-analytics - 使用 AngularJS 跟踪 Google Analytics 页面浏览量

javascript - Cypress 与 OpenLayers - 如何模拟 ctrl + 鼠标拖动

javascript - 解析 JSON 时期望 Object 但得到 String

javascript - 闪烁文字三秒

node.js - React js代码: 'MODULE_NOT_FOUND' ,无法运行reactjs?

reactjs - Web 应用程序的 firebase.analytics() 默认记录事件是什么?

javascript - ag-grid 上下文菜单图标自定义方法

css - React JS 中 css 转换结束后如何使用 setState?

javascript - 单一职责原则 React 重构

android - 谷歌分析阻止安卓应用