简体   繁体   English

谷歌分析仅在页面刷新时更新页面视图

[英]Google analytics only update page view when page is refreshed

I'm using react-ga for my google analytics, react-router for routing, and my navbar uses push in order to transfer between pages.我将 react-ga 用于我的谷歌分析,react-router 用于路由,我的导航栏使用推送来在页面之间传输。 Although I have tried to change it to <Link> and it did not solve the problem.尽管我尝试将其更改为<Link>并没有解决问题。

Here's a relevant piece of my app.js file:这是我的 app.js 文件的相关部分:

function App() {
  useEffect(() => {
    ReactGA.initialize("<myCode>");
    ReactGA.pageview(window.location.pathname + window.location.search);
  }, []);

  return (
    <div className="App">
      <Router>
        <Switch>
          <Route exact path="/" component={Homepage} />
          <Route path="/register" component={Register} />

The right page will be updated when I type the address in the address bar of my browser, or even switch the page using the navbar and then hit "refresh".当我在浏览器的地址栏中输入地址时,正确的页面将被更新,甚至使用导航栏切换页面然后点击“刷新”。 But it would not be updated if I only move pages through the navbar.但是,如果我只通过导航栏移动页面,它将不会被更新。

I do understand that this issue is most likely because this line:我明白这个问题很可能是因为这条线:

ReactGA.pageview(window.location.pathname + window.location.search);

Is probably not executed when I move between pages, but not sure what would be the best practice to fix it.当我在页面之间移动时可能不会执行,但不确定修复它的最佳实践是什么。

This is a relevant piece of my navbar:这是我的导航栏的相关部分:

        <div
          className={styles.navOption}
          onClick={() => {
            this.movePage("/"); // <--- Calls this.props.history.push
          }}

        >
          home
        </div>

You need to put the useEffect in every component you want analytics for, and not in the main app component, since you want different analytics for each module, and because it is the wrong place to write it since the App component renders only once in this case, so the useEffect you wrote won't happen each route you enter.您需要将 useEffect 放在您想要分析的每个组件中,而不是放在主应用程序组件中,因为您希望对每个模块进行不同的分析,并且因为 App 组件在此中仅呈现一次,因此编写它的位置不正确情况下,因此您编写的 useEffect 不会发生在您输入的每条路线上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM