如何为 React-Router 设置 Google Analytics? [英] How to set up Google Analytics for React-Router?
本文介绍了如何为 React-Router 设置 Google Analytics?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我的 React 站点上设置 Google Analytics,并且遇到了一些软件包,但没有一个具有我在示例方面的设置.希望有人能对此有所了解.
I'm trying set up Google Analytics on my react site, and have come across a few packages, but none of which has the kind of set up that I have in terms of examples. Was hoping someone could shed some light on this.
我正在查看的包是 react-ga.
我的 index.js
上的渲染方法如下所示.
My render method on my index.js
looks like this.
React.render((
<Router history={createBrowserHistory()}>
<Route path="/" component={App}>
<IndexRoute component={Home} onLeave={closeHeader}/>
<Route path="/about" component={About} onLeave={closeHeader}/>
<Route path="/gallery" component={Gallery} onLeave={closeHeader}/>
<Route path="/contact-us" component={Contact} onLeave={closeHeader}>
<Route path="/contact-us/:service" component={Contact} onLeave={closeHeader}/>
</Route>
<Route path="/privacy-policy" component={PrivacyPolicy} onLeave={closeHeader} />
<Route path="/feedback" component={Feedback} onLeave={closeHeader} />
</Route>
<Route path="*" component={NoMatch} onLeave={closeHeader}/>
</Router>), document.getElementById('root'));
推荐答案
保留对历史对象的引用.即
Keep a reference to your history object. i.e.
import { createBrowserHistory } from 'history';
var history = createBrowserHistory();
ReactDOM.render((
<Router history={history}>
[...]
然后添加一个监听器来记录每次浏览量.(这假设您已经以通常的方式设置了 window.ga
对象.)
Then add a listener to record each pageview. (This assumes you've already set up the window.ga
object in the usual manner.)
history.listen((location) => {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
});
这篇关于如何为 React-Router 设置 Google Analytics?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文