我已经设法使用 ReactGA 库为我的 React 应用程序设置了 Google Analytics,因此当用户导航时,它会将页面浏览发送到分析。
问题所在
我面临的问题是,我没有在初始页面加载时向谷歌发送任何分析,因为history.listen
方法仅在位置更改时触发。
我的设置
在我的项目的根目录中,我初始化连接:
const history = require("history").createBrowserHistory;
import { Router } from "react-router-dom"
ReactGA.initialize(envConstants.ANALYTICS_TRACKING_ID);
const MyApp = () => (
<Router history={history}>
<MyRoutes />
</Router>
)
由于我只想查看用户在哪些路由上,因此我的路由器中有以下内容:
const MyRoutes = props => {
props.history.listen(location => {
// won't see this on initial load, but navigating to another route will give me this
console.log("LISTENING")
})
return (...)
}
所以我想知道当我访问我的网站时,我如何解决这个问题并发送第一个/初始页面浏览量。我相信我无法用history.listen
方法实现这一目标。所以,我想我们必须添加一些我不太确定的其他功能。
我感谢我能得到的所有帮助。如果有什么不清楚的地方,请告诉我。
感谢您的阅读,祝你有美好的一天!
问题是初始页面加载时不会调用历史侦听,因为它仅在位置更改时调用。尝试如下操作
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ReactGA from 'react-ga';
const trackPageView = location => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
};
const initGa = history => {
ReactGA.initialize('UA-XXXXXX-X', {
debug: true
});
trackPageView(history.location);
history.listen(trackPageView);
};
const history = createHistory();
initGa(history);
ReactDOM.render((
<Router history={history}>
<Layout />
</Router>
), document.getElementById('root'));