8

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

  1. 主要的
  2. 服务
  3. 接触
  4. 个人资料(私人)
  5. ETC..

我需要使用 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-gainitGA()在每个呈现路由响应的组件上添加功能。initGA()我认为在每个组件中都复制是不对的。请问各位大神,怎么用react-ga?使用 react-ga 的正确方法是什么?

4

7 回答 7

12

这是使用钩子的方法。

应用程序.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路线改变时才会触发。首次加载页面时不会发生这种情况。为了解决这个问题,我在组件中添加了useEffect一个钩子。App如果用户重新加载站点,App将始终重新呈现。ReactGA.pageview(window.location.pathname + window.location.search)如果路线不是'/'.

于 2019-09-13T12:19:07.957 回答
11

为了使其工作需要使用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;
于 2018-10-09T16:38:50.620 回答
4

这是一个利用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>
  )
}
于 2020-06-28T10:49:50.693 回答
1

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

ReactGA.pageview(pagepath);

在您的路由中。

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

于 2018-10-09T15:26:11.803 回答
0

您可以使用 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 来解决这个问题。

于 2020-03-25T17:45:53.737 回答
0

在我意识到我正在使用 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();
   }, []);
于 2020-09-18T18:55:00.707 回答
0

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

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

为了确保您应该将您的initGA();ReactGAcomponentDidMount()脚本放在componentDidMount().

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

于 2021-11-11T13:43:37.087 回答