如何为 React-Router 设置 Google 分析?
How to set up Google Analytics for React-Router?
我正在尝试在我的 React 站点上设置 Google Analytics,并且遇到了一些包,但是 none 其中有我所拥有的那种设置例子。希望有人能对此有所了解。
我正在查看的包裹是,react-ga。
我 index.js
上的渲染方法如下所示。
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'));
保留对历史对象的引用。即
import { createBrowserHistory } from 'history';
var history = createBrowserHistory();
ReactDOM.render((
<Router history={history}>
[...]
然后添加一个侦听器来记录每个页面浏览量。 (假设您已经以通常的方式设置了 window.ga
对象。)
history.listen((location) => {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
});
首先,在您的 index.js 中设置 onUpdate 函数来调用 ga
import ga from 'ga.js';
onUpdate() {
console.log('=====GA=====>', location.pathname);
console.log('=====GA_TRACKING_CODE=====>', GA_TRACKING_CODE);
ga("send", "pageview", location.pathname);
}
render() {
return (
<Router onUpdate={this.onUpdate.bind(this)}>...</Router>
);
}
和ga.js:
'use strict';
if(typeof window !== 'undefined' && typeof GA_TRACKING_CODE !== 'undefined') {
(function(window, document, script, url, r, tag, firstScriptTag) {
window['GoogleAnalyticsObject']=r;
window[r] = window[r] || function() {
(window[r].q = window[r].q || []).push(arguments)
};
window[r].l = 1*new Date();
tag = document.createElement(script),
firstScriptTag = document.getElementsByTagName(script)[0];
tag.async = 1;
tag.src = url;
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
})(
window,
document,
'script',
'//www.google-analytics.com/analytics.js',
'ga'
);
var ga = window.ga;
ga('create', GA_TRACKING_CODE, 'auto');
module.exports = function() {
return window.ga.apply(window.ga, arguments);
};
} else {
module.exports = function() {console.log(arguments)};
}
鉴于 google 分析已加载并使用跟踪 ID 初始化。
这是使用 <Route>
组件跟踪页面浏览量的 react-router 版本 4 的解决方案。
<Route path="/" render={({location}) => {
if (typeof window.ga === 'function') {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
}
return null;
}} />
您只需在 <Router>
中渲染此组件(但不是 <Switch>
的直接子组件)。
发生的情况是,每当 location 道具发生变化时,它都会导致重新呈现此组件(实际上并未呈现任何内容),从而触发网页浏览。
如果您使用哈希或浏览器历史记录,您可以:
import trackingHit from 'tracking';
import { Router, browserHistory } from 'react-router';
browserHistory.listen(trackingHit);
// OR
import { Router, hashHistory } from 'react-router';
hashHistory.listen(trackingHit);
哪里./tracking.es6
export default function(location) {
console.log('New page hit', location.pathname);
// Do your shizzle here
}
请注意,如果您使用 react-router-4
中的 react-router-dom
包,您可以这样处理:
import { Router, Route } from 'react-router-dom';
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
const initGA = (history) => {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'YOUR_IDENTIFIER_HERE', 'auto');
ga('send', 'pageview');
history.listen((location) => {
console.log("tracking page view: " + location.pathname);
ga('send', 'pageview', location.pathname);
});
};
initGA(history);
class App extends Component { //eslint-disable-line
render() {
return
(<Router history={history} >
<Route exact path="/x" component={x} />
<Route exact path="/y" component={y} />
</Router>)
}
}
请注意,这需要您安装 history
软件包 (npm install history
)。这已经是 react-router-dom 的依赖项,因此您不会在此处添加任何页面权重。
另请注意:无法使用 BrowserRouter 组件并以这种方式检测您的 GA 跟踪。这没关系,因为 BrowserRouter component 只是 Router 对象的一个非常薄的包装器。我们在这里使用 <Router history={history}>
重新创建 BrowserRouter 功能,其中 const history = createBrowserHistory();
.
使用您的 index.js
进行基本的 react-ga 实现
var ReactGA = require('react-ga'); // require the react-ga module
ReactGA.initialize('Your-UA-ID-HERE'); // add your UA code
function logPageView() { // add this function to your component
ReactGA.set({ page: window.location.pathname + window.location.search });
ReactGA.pageview(window.location.pathname + window.location.search);
}
React.render((
<Router history={createBrowserHistory()} onUpdate={logPageView} > // insert onUpdate props here
<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'));
我正在使用 React Router v4 和 Google Analytics Global Site Tag,这在撰写本文时似乎是推荐的。
这是我的解决方案:
从 react-router-dom
:
创建一个包裹在 withRouter 中的组件
import React from 'react';
import { withRouter } from 'react-router-dom';
import { GA_TRACKING_ID } from '../config';
class GoogleAnalytics extends React.Component {
componentWillUpdate ({ location, history }) {
const gtag = window.gtag;
if (location.pathname === this.props.location.pathname) {
// don't log identical link clicks (nav links likely)
return;
}
if (history.action === 'PUSH' &&
typeof(gtag) === 'function') {
gtag('config', GA_TRACKING_ID, {
'page_title': document.title,
'page_location': window.location.href,
'page_path': location.pathname
});
}
}
render () {
return null;
}
}
export default withRouter(GoogleAnalytics);
只需在您的路由器中添加组件(我相信理想情况下是在任何匹配的路由和任何 Switch 组件之后,因为分析功能不应优先于您的站点呈现):
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import IndexPage from './IndexPage';
import NotFoundPage from './NotFoundPage';
import GoogleAnalytics from './GoogleAnalytics';
const App = () => (
<Router>
<Switch>
<Route exact path="/" component={IndexPage} />
<Route component={NotFoundPage} />
</Switch>
<GoogleAnalytics />
</Router>
);
如前所述:
withRouter will re-render its component every time the route changes with the
same props as render props
所以当路线改变时,GoogleAnalytics
组件将更新,它将接收新的位置作为道具,history.action
将是 PUSH
用于新的历史记录项或POP
表示向后浏览历史记录(我认为这不应触发页面视图,但您可以根据需要调整 componentWillUpdate
中的 if 语句(您甚至可以尝试 componentDidUpdate
改为 this.props
,但我不确定哪个更好))。
我建议使用非常轻便且易于配置的优秀 react-router-ga
软件包,尤其是在使用 BrowserRouter
包装器时。
导入组件:
import Analytics from 'react-router-ga';
然后只需在 BrowserRouter
中添加 <Analytics>
:
<BrowserRouter>
<Analytics id="UA-ANALYTICS-1">
<Switch>
<Route path="/somewhere" component={SomeComponent}/>
</Switch>
</Analytics>
</BrowserRouter>
Always go with the library's recommended way
在 React-GA 文档中,他们添加了推荐与 React Router 一起使用的社区组件:https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker
实施
import withTracker from './withTracker';
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Route component={withTracker(App, { /* additional attributes */ } )} />
</ConnectedRouter>
</Provider>,
document.getElementById('root'),
);
代码
import React, { Component, } from "react";
import GoogleAnalytics from "react-ga";
GoogleAnalytics.initialize("UA-0000000-0");
const withTracker = (WrappedComponent, options = {}) => {
const trackPage = page => {
GoogleAnalytics.set({
page,
...options,
});
GoogleAnalytics.pageview(page);
};
// eslint-disable-next-line
const HOC = class extends Component {
componentDidMount() {
// eslint-disable-next-line
const page = this.props.location.pathname + this.props.location.search;
trackPage(page);
}
componentDidUpdate(prevProps) {
const currentPage =
prevProps.location.pathname + prevProps.location.search;
const nextPage =
this.props.location.pathname + this.props.location.search;
if (currentPage !== nextPage) {
trackPage(nextPage);
}
}
render() {
return <WrappedComponent {...this.props} />;
}
};
return HOC;
};
export default withTracker;
这里是跟踪所有路径的最简单方法,并带有一些变通方法:
npm i --save history react-ga
创建文件history.js
import { createBrowserHistory } from "history"
import ReactGA from "react-ga"
ReactGA.initialize(process.env.REACT_APP_GA)
const history = createBrowserHistory()
history.listen((location) => {
ReactGA.pageview(location.pathname)
})
// workaround for initial visit
if (window.performance && (performance.navigation.type === performance.navigation.TYPE_NAVIGATE)) {
ReactGA.pageview("/")
}
export default history
然后将其导入到 Router
设置的位置
import history from "./history"
...
class Route extends Component {
render() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={HomePage} />
...
</Switch>
</Router>
)
}
export default Route
References:
我建议使用细分分析库并关注 React quickstart guide to track page calls using the react-router 库。您可以允许 <Route />
组件在页面呈现时进行处理,并使用 componentDidMount
调用 page
调用。下面的示例显示了您可以执行此操作的一种方法:
const App = () => (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</div>
);
export default App;
export default class Home extends Component {
componentDidMount() {
window.analytics.page('Home');
}
render() {
return (
<h1>
Home page.
</h1>
);
}
}
我是 https://github.com/segmentio/analytics-react 的维护者。借助 Segment,如果您有兴趣尝试多种分析工具(我们支持 250 多个目的地),而无需编写任何额外代码,您将能够通过轻按开关来打开和关闭不同的目的地。
我喜欢 Mark Thomas Müller 的建议 here:
在你的index.js
import ReactGA from 'react-ga'
ReactGA.initialize('YourAnalyticsID')
ReactDOM.render(<App />, document.getElementById('root'))
你的路线在哪里:
import React, { Component } from 'react'
import { Router, Route } from 'react-router-dom'
import createHistory from 'history/createBrowserHistory'
import ReactGA from 'react-ga'
const history = createHistory()
history.listen(location => {
ReactGA.set({ page: location.pathname })
ReactGA.pageview(location.pathname)
})
export default class AppRoutes extends Component {
componentDidMount() {
ReactGA.pageview(window.location.pathname)
}
render() {
return (
<Router history={history}>
<div>
<Route path="/your" component={Your} />
<Route path="/pages" component={Pages} />
<Route path="/here" component={Here} />
</div>
</Router>
)
}
}
简短、可扩展且简单:)
基于@david-l-walsh 和@bozdoz 的建议
我创建了一个执行 window.ga('set','page','{currentUrl})
和 window.ga('send', 'pageview');
函数的 HOC,可以很容易地直接在路由器页面中使用...
这是 HOC:
import React from 'react';
import { history } from '../../store'; // or wherever you createBrowserHistory(); invokation is
function withGAHistoryTrack(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { location } = history;
const page = location.pathname + location.search;
if (typeof window.ga === 'function') {
window.ga('set', 'page', page);
window.ga('send', 'pageview');
}
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
export default withGAHistoryTrack;
在路由页面中是这样使用的:
<Route
path={'yourPath'}
component={withGAHistoryTrack(yourComponent)}
exact
/>
为了在某些事件(如 onClick 等)上动态更新 url,可以使用以下内容:
//Imports
import ReactGA from "react-ga";
import { createBrowserHistory } from "history";
// Add following on some event, like onClick (depends on your requirement)
const history = createBrowserHistory();
ReactGA.initialize("<Your-UA-ID-HERE>");
ReactGA.pageview(history.location.pathname);
因为 react-router v5.1.0
使用 useLocation
可以更容易地解决这个问题。
usePageTracking.js
import { useEffect} from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";
const usePageTracking = () => {
const location = useLocation();
useEffect(() => {
ReactGA.initialize("UA-000000000-0");
ReactGA.pageview(location.pathname + location.search);
}, [location]);
};
export default usePageTracking;
App.js
const App = () => {
usePageTracking();
return (...);
};
另请参阅:
这里有一个更聪明的版本:
usePageTracking.js
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";
const usePageTracking = () => {
const location = useLocation();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if (!window.location.href.includes("localhost")) {
ReactGA.initialize("UA-000000000-0");
}
setInitialized(true);
}, []);
useEffect(() => {
if (initialized) {
ReactGA.pageview(location.pathname + location.search);
}
}, [initialized, location]);
};
export default usePageTracking;
我正在尝试在我的 React 站点上设置 Google Analytics,并且遇到了一些包,但是 none 其中有我所拥有的那种设置例子。希望有人能对此有所了解。
我正在查看的包裹是,react-ga。
我 index.js
上的渲染方法如下所示。
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'));
保留对历史对象的引用。即
import { createBrowserHistory } from 'history';
var history = createBrowserHistory();
ReactDOM.render((
<Router history={history}>
[...]
然后添加一个侦听器来记录每个页面浏览量。 (假设您已经以通常的方式设置了 window.ga
对象。)
history.listen((location) => {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
});
首先,在您的 index.js 中设置 onUpdate 函数来调用 ga
import ga from 'ga.js';
onUpdate() {
console.log('=====GA=====>', location.pathname);
console.log('=====GA_TRACKING_CODE=====>', GA_TRACKING_CODE);
ga("send", "pageview", location.pathname);
}
render() {
return (
<Router onUpdate={this.onUpdate.bind(this)}>...</Router>
);
}
和ga.js:
'use strict';
if(typeof window !== 'undefined' && typeof GA_TRACKING_CODE !== 'undefined') {
(function(window, document, script, url, r, tag, firstScriptTag) {
window['GoogleAnalyticsObject']=r;
window[r] = window[r] || function() {
(window[r].q = window[r].q || []).push(arguments)
};
window[r].l = 1*new Date();
tag = document.createElement(script),
firstScriptTag = document.getElementsByTagName(script)[0];
tag.async = 1;
tag.src = url;
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
})(
window,
document,
'script',
'//www.google-analytics.com/analytics.js',
'ga'
);
var ga = window.ga;
ga('create', GA_TRACKING_CODE, 'auto');
module.exports = function() {
return window.ga.apply(window.ga, arguments);
};
} else {
module.exports = function() {console.log(arguments)};
}
鉴于 google 分析已加载并使用跟踪 ID 初始化。
这是使用 <Route>
组件跟踪页面浏览量的 react-router 版本 4 的解决方案。
<Route path="/" render={({location}) => {
if (typeof window.ga === 'function') {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
}
return null;
}} />
您只需在 <Router>
中渲染此组件(但不是 <Switch>
的直接子组件)。
发生的情况是,每当 location 道具发生变化时,它都会导致重新呈现此组件(实际上并未呈现任何内容),从而触发网页浏览。
如果您使用哈希或浏览器历史记录,您可以:
import trackingHit from 'tracking';
import { Router, browserHistory } from 'react-router';
browserHistory.listen(trackingHit);
// OR
import { Router, hashHistory } from 'react-router';
hashHistory.listen(trackingHit);
哪里./tracking.es6
export default function(location) {
console.log('New page hit', location.pathname);
// Do your shizzle here
}
请注意,如果您使用 react-router-4
中的 react-router-dom
包,您可以这样处理:
import { Router, Route } from 'react-router-dom';
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
const initGA = (history) => {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'YOUR_IDENTIFIER_HERE', 'auto');
ga('send', 'pageview');
history.listen((location) => {
console.log("tracking page view: " + location.pathname);
ga('send', 'pageview', location.pathname);
});
};
initGA(history);
class App extends Component { //eslint-disable-line
render() {
return
(<Router history={history} >
<Route exact path="/x" component={x} />
<Route exact path="/y" component={y} />
</Router>)
}
}
请注意,这需要您安装 history
软件包 (npm install history
)。这已经是 react-router-dom 的依赖项,因此您不会在此处添加任何页面权重。
另请注意:无法使用 BrowserRouter 组件并以这种方式检测您的 GA 跟踪。这没关系,因为 BrowserRouter component 只是 Router 对象的一个非常薄的包装器。我们在这里使用 <Router history={history}>
重新创建 BrowserRouter 功能,其中 const history = createBrowserHistory();
.
使用您的 index.js
进行基本的 react-ga 实现var ReactGA = require('react-ga'); // require the react-ga module
ReactGA.initialize('Your-UA-ID-HERE'); // add your UA code
function logPageView() { // add this function to your component
ReactGA.set({ page: window.location.pathname + window.location.search });
ReactGA.pageview(window.location.pathname + window.location.search);
}
React.render((
<Router history={createBrowserHistory()} onUpdate={logPageView} > // insert onUpdate props here
<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'));
我正在使用 React Router v4 和 Google Analytics Global Site Tag,这在撰写本文时似乎是推荐的。
这是我的解决方案:
从 react-router-dom
:
import React from 'react';
import { withRouter } from 'react-router-dom';
import { GA_TRACKING_ID } from '../config';
class GoogleAnalytics extends React.Component {
componentWillUpdate ({ location, history }) {
const gtag = window.gtag;
if (location.pathname === this.props.location.pathname) {
// don't log identical link clicks (nav links likely)
return;
}
if (history.action === 'PUSH' &&
typeof(gtag) === 'function') {
gtag('config', GA_TRACKING_ID, {
'page_title': document.title,
'page_location': window.location.href,
'page_path': location.pathname
});
}
}
render () {
return null;
}
}
export default withRouter(GoogleAnalytics);
只需在您的路由器中添加组件(我相信理想情况下是在任何匹配的路由和任何 Switch 组件之后,因为分析功能不应优先于您的站点呈现):
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import IndexPage from './IndexPage';
import NotFoundPage from './NotFoundPage';
import GoogleAnalytics from './GoogleAnalytics';
const App = () => (
<Router>
<Switch>
<Route exact path="/" component={IndexPage} />
<Route component={NotFoundPage} />
</Switch>
<GoogleAnalytics />
</Router>
);
如前所述:
withRouter will re-render its component every time the route changes with the same props as render props
所以当路线改变时,GoogleAnalytics
组件将更新,它将接收新的位置作为道具,history.action
将是 PUSH
用于新的历史记录项或POP
表示向后浏览历史记录(我认为这不应触发页面视图,但您可以根据需要调整 componentWillUpdate
中的 if 语句(您甚至可以尝试 componentDidUpdate
改为 this.props
,但我不确定哪个更好))。
我建议使用非常轻便且易于配置的优秀 react-router-ga
软件包,尤其是在使用 BrowserRouter
包装器时。
导入组件:
import Analytics from 'react-router-ga';
然后只需在 BrowserRouter
中添加 <Analytics>
:
<BrowserRouter>
<Analytics id="UA-ANALYTICS-1">
<Switch>
<Route path="/somewhere" component={SomeComponent}/>
</Switch>
</Analytics>
</BrowserRouter>
Always go with the library's recommended way
在 React-GA 文档中,他们添加了推荐与 React Router 一起使用的社区组件:https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker
实施
import withTracker from './withTracker';
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Route component={withTracker(App, { /* additional attributes */ } )} />
</ConnectedRouter>
</Provider>,
document.getElementById('root'),
);
代码
import React, { Component, } from "react";
import GoogleAnalytics from "react-ga";
GoogleAnalytics.initialize("UA-0000000-0");
const withTracker = (WrappedComponent, options = {}) => {
const trackPage = page => {
GoogleAnalytics.set({
page,
...options,
});
GoogleAnalytics.pageview(page);
};
// eslint-disable-next-line
const HOC = class extends Component {
componentDidMount() {
// eslint-disable-next-line
const page = this.props.location.pathname + this.props.location.search;
trackPage(page);
}
componentDidUpdate(prevProps) {
const currentPage =
prevProps.location.pathname + prevProps.location.search;
const nextPage =
this.props.location.pathname + this.props.location.search;
if (currentPage !== nextPage) {
trackPage(nextPage);
}
}
render() {
return <WrappedComponent {...this.props} />;
}
};
return HOC;
};
export default withTracker;
这里是跟踪所有路径的最简单方法,并带有一些变通方法:
npm i --save history react-ga
创建文件history.js
import { createBrowserHistory } from "history"
import ReactGA from "react-ga"
ReactGA.initialize(process.env.REACT_APP_GA)
const history = createBrowserHistory()
history.listen((location) => {
ReactGA.pageview(location.pathname)
})
// workaround for initial visit
if (window.performance && (performance.navigation.type === performance.navigation.TYPE_NAVIGATE)) {
ReactGA.pageview("/")
}
export default history
然后将其导入到 Router
import history from "./history"
...
class Route extends Component {
render() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={HomePage} />
...
</Switch>
</Router>
)
}
export default Route
References:
我建议使用细分分析库并关注 React quickstart guide to track page calls using the react-router 库。您可以允许 <Route />
组件在页面呈现时进行处理,并使用 componentDidMount
调用 page
调用。下面的示例显示了您可以执行此操作的一种方法:
const App = () => (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</div>
);
export default App;
export default class Home extends Component {
componentDidMount() {
window.analytics.page('Home');
}
render() {
return (
<h1>
Home page.
</h1>
);
}
}
我是 https://github.com/segmentio/analytics-react 的维护者。借助 Segment,如果您有兴趣尝试多种分析工具(我们支持 250 多个目的地),而无需编写任何额外代码,您将能够通过轻按开关来打开和关闭不同的目的地。
我喜欢 Mark Thomas Müller 的建议 here:
在你的index.js
import ReactGA from 'react-ga'
ReactGA.initialize('YourAnalyticsID')
ReactDOM.render(<App />, document.getElementById('root'))
你的路线在哪里:
import React, { Component } from 'react'
import { Router, Route } from 'react-router-dom'
import createHistory from 'history/createBrowserHistory'
import ReactGA from 'react-ga'
const history = createHistory()
history.listen(location => {
ReactGA.set({ page: location.pathname })
ReactGA.pageview(location.pathname)
})
export default class AppRoutes extends Component {
componentDidMount() {
ReactGA.pageview(window.location.pathname)
}
render() {
return (
<Router history={history}>
<div>
<Route path="/your" component={Your} />
<Route path="/pages" component={Pages} />
<Route path="/here" component={Here} />
</div>
</Router>
)
}
}
简短、可扩展且简单:)
基于@david-l-walsh 和@bozdoz 的建议
我创建了一个执行 window.ga('set','page','{currentUrl})
和 window.ga('send', 'pageview');
函数的 HOC,可以很容易地直接在路由器页面中使用...
这是 HOC:
import React from 'react';
import { history } from '../../store'; // or wherever you createBrowserHistory(); invokation is
function withGAHistoryTrack(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { location } = history;
const page = location.pathname + location.search;
if (typeof window.ga === 'function') {
window.ga('set', 'page', page);
window.ga('send', 'pageview');
}
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
export default withGAHistoryTrack;
在路由页面中是这样使用的:
<Route
path={'yourPath'}
component={withGAHistoryTrack(yourComponent)}
exact
/>
为了在某些事件(如 onClick 等)上动态更新 url,可以使用以下内容:
//Imports
import ReactGA from "react-ga";
import { createBrowserHistory } from "history";
// Add following on some event, like onClick (depends on your requirement)
const history = createBrowserHistory();
ReactGA.initialize("<Your-UA-ID-HERE>");
ReactGA.pageview(history.location.pathname);
因为 react-router v5.1.0
使用 useLocation
可以更容易地解决这个问题。
usePageTracking.js
import { useEffect} from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";
const usePageTracking = () => {
const location = useLocation();
useEffect(() => {
ReactGA.initialize("UA-000000000-0");
ReactGA.pageview(location.pathname + location.search);
}, [location]);
};
export default usePageTracking;
App.js
const App = () => {
usePageTracking();
return (...);
};
另请参阅:
这里有一个更聪明的版本:
usePageTracking.js
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";
const usePageTracking = () => {
const location = useLocation();
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if (!window.location.href.includes("localhost")) {
ReactGA.initialize("UA-000000000-0");
}
setInitialized(true);
}, []);
useEffect(() => {
if (initialized) {
ReactGA.pageview(location.pathname + location.search);
}
}, [initialized, location]);
};
export default usePageTracking;