我通过以下方式使用React Router设置React-ga:
...
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import {Provider} from 'react-redux';
import ReactGA from 'react-ga';
ReactGA.initialize('MY TRACKING CODE', {
debug: true
});
const history = createHistory();
history.listen((location) => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<Layout />
</Router>
</Provider>
), document.getElementById('root'));
registerServiceWorker();
如果我已经在页面上并访问另一条路径,我会在控制台上获得以下内容:
log.js:2 [react-ga] called ga('set', fieldsObject);
log.js:2 [react-ga] with fieldsObject: {"page":"/products"}
log.js:2 [react-ga] called ga('send', 'pageview', path);
log.js:2 [react-ga] with path: /products
但是,如果我是第一次访问该页面(通过点击链接或直接在浏览器上输入路径),我在控制台上没有任何内容。
为了计算第一次访问,我是否缺少任何步骤?
答案 0 :(得分:1)
对于遇到同样问题的人来说,问题是历史监听不会在初始页面加载时调用,因为只有在位置发生变化时才会调用它。
以下设置对我有用:
...
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import {Provider} from 'react-redux';
import ReactGA from 'react-ga';
const trackPageView = location => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
};
const initGa = history => {
ReactGA.initialize('MY TRACKING CODE', {
debug: true
});
trackPageView(history.location);
history.listen(trackPageView);
};
const history = createHistory();
initGa(history);
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<Layout />
</Router>
</Provider>
), document.getElementById('root'));
registerServiceWorker();