[英]Google Analytics setup for React
我已經設法使用ReactGA 庫為我的 React 應用程序設置了 Google Analytics,因此當用戶四處瀏覽時,它會將瀏覽量發送到分析。
我面臨的問題是我沒有在初始頁面加載時向 google 發送任何分析,因為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'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.