我已经用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但是,如果我第一次访问该页面(通过单击链接或直接在浏览器上键入路径),我在控制台上得不到任何内容。
为了计算第一次访问,我是否遗漏了什么步骤?
发布于 2018-03-03 22:15:02
对于任何有同样问题的人来说,问题是历史记录侦听不会在初始页面加载时调用,因为它只在位置更改时调用。
以下设置适用于我:
...
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(); https://stackoverflow.com/questions/48992599
复制相似问题