如何让 Google Analytics 与 React 一起工作

How to get Google Analytics to work with React

我正在尝试跟踪每个页面,但 google 仅在我每次单击刷新按钮时注册一个视图。不是当我路由到一条新路径时。有人知道如何进行这项工作吗?

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; 

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

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;