我尝试在我的反应网站上设置Google Analytics,并且遇到了一些软件包,但是没有一个软件包具有我在示例方面的设置。希望有人可以对此有所了解。
我正在查看的包裹是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'));
答案 0 :(得分:63)
保留对历史对象的引用。即。
import createBrowserHistory from 'history/createBrowserHistory';
var history = createBrowserHistory();
ReactDOM.render((
<Router history={history}>
[...]
然后添加一个监听器来记录每个综合浏览量。 (这假设您已经以通常的方式设置了window.ga
对象。)
history.listen(function (location) {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
});
答案 1 :(得分:23)
鉴于谷歌分析已加载并使用跟踪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>
的直接子项)。
无论何时位置道具发生变化,都会导致重新渲染此组件(实际上不渲染任何内容),从而触发网页浏览。
答案 2 :(得分:18)
我使用的是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将在每次路由更改时重新呈现其组件 与渲染道具相同的道具
因此,当路线发生变化时,GoogleAnalytics
组件会更新,它会收到新位置作为道具,而history.action
将PUSH
作为新的历史记录项目或POP
1}}在历史记录中向后发出信号(我认为不应该触发页面视图,但您可以根据需要调整componentWillUpdate
中的if语句(您甚至可以尝试componentDidUpdate
}而this.props
代替,但我不确定哪个更好))。
答案 3 :(得分:17)
请注意,如果您使用react-router-dom
中的react-router-4
包,则可以这样处理:
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组件和仪器以此方式跟踪。这没关系,因为BrowserRouter component只是路由器对象周围的一个非常薄的包装器。我们使用<Router history={history}>
const history = createBrowserHistory();
。
答案 4 :(得分:11)
由于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;
答案 5 :(得分:8)
我建议使用非常轻量且易于配置的优秀react-router-ga
包,尤其是在使用BrowserRouter
包装器时。
导入组件:
import Analytics from 'react-router-ga';
然后只需在<Analytics>
:
BrowserRouter
即可
<BrowserRouter>
<Analytics id="UA-ANALYTICS-1">
<Switch>
<Route path="/somewhere" component={SomeComponent}/>
</Switch>
</Analytics>
</BrowserRouter>
答案 6 :(得分:4)
首先,在你的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)};
}
答案 7 :(得分:3)
始终遵循图书馆推荐的方式
在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;
答案 8 :(得分:0)
如果您使用哈希或浏览器历史记录,则可以执行以下操作:
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
}
答案 9 :(得分:0)
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'));
答案 10 :(得分:0)
这是通过一些解决方法来跟踪所有路径的最简单方法:
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
参考文献:
答案 11 :(得分:0)
我建议使用细分分析库,并遵循React quickstart guide使用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的维护者。如果您有兴趣尝试使用多种分析工具(我们支持超过250个目的地),而无需编写任何其他代码,则可以使用细分功能通过切换开关来打开和关闭不同的目的地。
答案 12 :(得分:0)
我喜欢Mark ThomasMüller的建议here:
在您的 index.js
node_type
您的路线在哪里
import ReactGA from 'react-ga'
ReactGA.initialize('YourAnalyticsID')
ReactDOM.render(<App />, document.getElementById('root'))
简短,可伸缩且简单:)
答案 13 :(得分:0)
基于@ 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
/>
答案 14 :(得分:0)
要动态更新某些事件(例如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);