首页 > 解决方案 > 如何让 Google Analytics 与 React 一起工作

问题描述

我正在尝试跟踪每个页面,但每次单击刷新按钮时谷歌只会注册一个视图。当iv'e路由到新路径时不会。有人对如何使这项工作有想法吗?

import React, {useEffect} from 'react';
import { BrowserRouter, Switch, Route } from "react-router-dom";
import OurWork from "./ourWork/ourWork"
import Home from "./home/Home"
import Packages from "./packages/Packages"
import Contacts from "./contact/Contact"
import ReactGA from 'react-ga'
import createHistory from 'history/createBrowserHistory'
const Routes = () => {
    const {
        ContactPage
    } = Contacts();
    const history = createHistory()
    history.listen(location => {
        ReactGA.set({ page: location.pathname });
        ReactGA.pageview(location.pathname);
    });
    useEffect(() => {
         ReactGA.pageview(window.location.pathname + window.location.search)
     }, [history])
    return(
        <BrowserRouter history={history}>
            <Switch>
                <Route path="/" exact component={Home} /> 
                <Route path="/ourwork" exact component={OurWork} /> 
                <Route path="/packages" exact component={Packages} /> 
                <Route path="/Contact" exact component={ContactPage} /> 
            </Switch>
        </BrowserRouter>
    )
}
export default Routes; 

标签: reactjsgoogle-analyticsreact-routeruse-effect

解决方案


看起来与此处描述的相同问题。尝试更改<BrowserRouter history={history}>为并从中<Router history={history}>导入,如下所示:Router"react-router-dom"

import React, {useEffect} from 'react';
import { Router, Switch, Route } from "react-router-dom";
import OurWork from "./ourWork/ourWork"
import Home from "./home/Home"
import Packages from "./packages/Packages"
import Contacts from "./contact/Contact"
import ReactGA from 'react-ga'
import createHistory from 'history/createBrowserHistory'
const Routes = () => {
    const {
        ContactPage
    } = Contacts();
    const history = createHistory()
    history.listen(location => {
        ReactGA.set({ page: location.pathname });
        ReactGA.pageview(location.pathname);
    });
    useEffect(() => {
         ReactGA.pageview(window.location.pathname + window.location.search)
     }, [history])
    return(
        <Router history={history}>
            <Switch>
                <Route path="/" exact component={Home} /> 
                <Route path="/ourwork" exact component={OurWork} /> 
                <Route path="/packages" exact component={Packages} /> 
                <Route path="/Contact" exact component={ContactPage} /> 
            </Switch>
        </Router>
    )
}
export default Routes; 

推荐阅读