【问题标题】:How to use Google Analytics with React?如何在 React 中使用 Google Analytics?
【发布时间】:2019-03-14 10:24:48
【问题描述】:

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

  1. 主要
  2. 服务
  3. 联系方式
  4. 个人资料(私人)
  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);
}

我的App class 看起来像:

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 的正确使用方法是什么?

【问题讨论】:

    标签: javascript reactjs google-analytics react-ga


    【解决方案1】:

    你应该只初始化一次,然后再使用

    ReactGA.pageview(pagepath);
    

    在您的路由中。

    演示:https://github.com/react-ga/react-ga/tree/master/demo

    【讨论】:

    • “在你的路由中”是什么意思?能否给出更详细的代码示例?
    • 这样跟踪不起作用。给出警告:react-ga.js:88 [react-ga] 必须先调用 ReactGA.initialize 否则应手动加载 GoogleAnalytics
    • 我在 index.js 和每个页面上添加了ReactGA.initialize ReactGA.pageview('...'),但控制台上总是有一个警报 ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually。所以我决定在每一页上添加ReactGA.initialize
    【解决方案2】:

    要使其正常工作,需要使用Router 功能。 所以在 App 组件中import { Router } from 'react-router-dom'。它必须是路由器而不是浏览器路由器。

    然后import createHistory from 'history/createBrowserHistory'

    const history = createHistory()
    ReactGA.initialize('UA-000000-1');
    history.listen((location, action) => {
        ReactGA.pageview(location.pathname + location.search);
        console.log(location.pathname)
    });
    

    此代码将在每次路线更改时触发!

    比给你的路由器组件一个历史属性。

    完整代码:

    import React, { Component } from 'react';
    import { Router, Route, Switch } from 'react-router-dom';
    import createHistory from 'history/createBrowserHistory'
    import Main from './components/pages/Main';
    import ReactGA from 'react-ga';
    
    
    const history = createHistory()
    ReactGA.initialize('UA-00000000-1');
    history.listen((location, action) => {
        ReactGA.pageview(location.pathname + location.search);
        console.log(location.pathname)
    });
    
    class App extends Component {
    
        render() {
            return (
    
                <Router history={history}>
                    <div className="App">
    
                        <Switch>
                            <Route exact path="/" component={Main} />
                            <Route exact path="/signup" component={SignupLayout} />
                            <Route component={PublicLayout} />
                        </Switch>
    
                    </div>
                </Router>
            );
        }
    }
    
    export default App;
    

    【讨论】:

    • 所以使用它,我们不需要在 componentDidMount() / componentWillMount() 中的每个组件上调用 initGA() ?
    • 这个答案没问题,但您不会在分析中保存第一页加载。 history.listen 只会在路由改变时触发。首次加载页面时不会发生这种情况。
    • (与问题无关)但如果您不需要它们,请不要创建类。请改用功能组件。我个人喜欢使用class,但仅在需要时使用。
    • @slinden 旧评论,但也许可以帮助其他人:注册第一个页面加载只需在 ReactGA.initialize 之后立即启动 ReactGA.pageview 函数,仅此而已
    【解决方案3】:

    这是使用钩子的方法。

    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 钩子。如果用户重新加载站点,App 将始终重新呈现。如果路由不是'/'ReactGA.pageview(window.location.pathname + window.location.search) 确保我们将重新加载归因于正确的路由。

    【讨论】:

    • 你确定这行得通吗?看起来useEffect 只会被调用一次!
    • 它只需要调用一次。该挂钩仅记录第一个页面加载。其余页面加载将记录在browserHistory.listen even 监听器中。
    • 我使用了您的解决方案,它对我很有用。谢谢你。 +1
    【解决方案4】:

    你可以使用 service.js 文件来解决这个问题,你必须制作多个导出器

    import ReactGA from 'react-ga';
    
    export const GAInit = (TrackingID) => {
       ReactGA.initialize(TrackingID)
    }
    
    export const GAEvent = (category, action) => {
    ReactGA.initialize('TrackingIDHere')   
    ReactGA.event({
       category,
       action
    })
    }
    
    // export pageview and more...
    

    从 App.js 导入并初始化和使用您不需要每次都初始化的服务。

    或者你可以使用脚本代替 react-ga 来解决这个问题。

    【讨论】:

      【解决方案5】:

      这是利用 React Router V5.1 中发布的useLocation() 的解决方案。

      这种方法的好处是它与BrowserRouter 兼容,如果您希望继续使用它。

      import React, { useEffect } from 'react';
      import { useLocation,} from 'react-router-dom';
      import ReactGA from 'react-ga';
      
      // Init Google Analytics
      ReactGA.initialize('UA-00000000-1');
      
      const App = () => {
        const location = useLocation();
      
        // Fired on every route change
        useEffect(() => {
          ReactGA.pageview(location.pathname + location.search);
        }, [location]);
      
        return (
          <div className="App"></div>
        )
      }
      

      【讨论】:

      • 这是最简单的实现,目前可以全面运行,谢谢!
      【解决方案6】:

      在我意识到我在使用 HashRouter 之前,我没有得到路径(总是“/”)。如果是这种情况,那么您可以应用以下内容:

      import React, { useState, useEffect } from 'react';
      import { Route, Switch, NavLink, HashRouter as Router } from 'react-router-dom';
      import ReactGA from 'react-ga';
      import { createHashHistory } from 'history';
      
      const App = () => {
         ReactGA.initialize(trackingId);
         const browserHistory = createHashHistory();
         browserHistory.listen((location, action) => {
            ReactGA.pageview(location.pathname + location.search);
      })
      
      // Activate Google Analytics
      useEffect(() => {
          ReactGA.pageview(window.location.pathname + window.location.search);
      }, []);
      }
      

      顺便说一句,不建议将您的 Google Analytics tracking_id 放在客户端。下面是更新后的代码,以更安全的方式,使用 axios 从服务器检索 tracking_id:

          useEffect(() => {
              const getTrackingID = async () => {
                  await axios.get(`${url}/ga/tracking_id`, {
                     headers: { 'Content-Type': 'application/json' }
                  })
                  .then(res => {
                      if (res.status === 204) {
                          console.log('No GA tracking_id found');
                      } else if (res.status === 200) {
                          const trackingId = res.data;
                          ReactGA.initialize(trackingId);
                          // Capture 1st load in home page
                          ReactGA.pageview(window.location.pathname + window.location.search);
                          // Capture any subsequent page change
                          browserHistory.listen((location) => {
                              ReactGA.pageview(location.pathname + location.search);
                          });
                      }
                  })
                  .catch(err => {
                      console.log('Error while retrieving GA tracking_id', err);
                  });
             };
             getTrackingID();
         }, []);
      

      【讨论】:

        【解决方案7】:

        这是避免在每个组件上“初始化”GA 的解决方法。

        基本上,确保运行的第一个 ReactGA 脚本是ReactGA.initialize('UA-00000000-1');

        为了确保您应该将 initGA(); 放在 componentDidMount() 之外,并将其余的 ReactGA 脚本放在 componentDidMount() 内。

        我知道这是一篇旧帖子,但所有答案都涉及路线跟踪,但不是这个实际问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-08-16
          • 1970-01-01
          • 2016-04-22
          • 2015-07-24
          • 1970-01-01
          • 1970-01-01
          • 2023-02-10
          相关资源
          最近更新 更多