HashRouter和Google Analytics无法跟踪单个路径



我已经尝试了各种解决方案,我目前正在使用它,不幸的是GA只跟踪一条路径('/'(

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../sass/main.scss';
import {
HashRouter,
Route,
Switch,
} from 'react-router-dom';
const history = createHistory()
ReactGA.initialize('UA-XXXXXXX-1');
history.listen((location, action) => {
ReactGA.pageview(location.pathname + location.search);
console.log(location.pathname)
});
class Index extends Component {

render() {
return (
<>
<HashRouter history={history} >
<Route />
<ScrollUpButton ContainerClassName="AnyClassForContainer" />
<Header />
<Switch history={history}>
<Route exact path={"/"} component={() => <HomePage />}/>
<Route exact path={"/test"} component={() => <CategoryLinksNextPrev />}/>
<Route exact path={"/contact"} component={() => <Contact />}/>
<Route exact path={"/car/:category/"} component={CarCategory} />
<Route exact path={"/car/:category/:carname"} component={CarOnePageMain} />
<Route path="*" component={NotFound} />
</Switch>
<Footer />
</HashRouter>
</>
)
}
}
ReactDOM.render(<Index />, document.getElementById("index"));

在谷歌分析中,它只向我显示了一个子页面,并且准确地指向index.html

更新

我找到了一个非常简单的解决办法。https://www.npmjs.com/package/react-router-ga

这就是我现在的代码:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../sass/main.scss';
import {
HashRouter,
Route,
Switch,
} from 'react-router-dom';
import Analytics from 'react-router-ga';
class Index extends Component {
render() {
return (
<>
<HashRouter >
<Analytics id="UA-xxxxxxx-1" debug>
<ScrollUpButton ContainerClassName="AnyClassForContainer" />
<Header />
<Switch history={history}>
<Route exact path={"/"} component={() => <HomePage />}/>
<Route exact path={"/test"} component={() => <CategoryLinksNextPrev />}/>
<Route exact path={"/contact"} component={() => <Contact />}/>
<Route exact path={"/car/:category/"} component={CarCategory} />
<Route exact path={"/car/:category/:carname"} component={CarOnePageMain} />
<Route path="*" component={NotFound} />
</Switch>
<Footer />
</Analytics>
</HashRouter>
</>
)
}
}
ReactDOM.render(<Index />, document.getElementById("index"));

我最近遇到了类似的问题。

看起来Google Analytics加载在页面加载上。如果你点击一个链接,GA将再次运行,因为新页面是用一个新的URL从头开始加载的。

当用户在您的单页应用程序中移动时,您必须手动激发GA页面视图。

更多信息请点击此处-https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

最新更新