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

Google analytics only update page view when page is refreshed

我正在使用 react-ga 进行 google 分析,使用 react-router 进行路由,我的导航栏使用 push 来在页面之间传输。 虽然我试过改成<Link>,但还是没有解决问题。

这是我的 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} />

当我在浏览器的地址栏中输入地址,或者甚至使用导航栏切换页面然后点击“刷新”时,右侧的页面将被更新。但是如果我只通过导航栏移动页面,它就不会更新。

我知道这个问题很可能是因为这一行:

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

当我在页面之间移动时可能不会执行,但不确定修复它的最佳做法是什么。

这是我的导航栏的相关部分:

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

        >
          home
        </div>

您需要将 useEffect 放在您想要分析的每个组件中,而不是在主应用程序组件中,因为您希望对每个模块进行不同的分析, 因为在这种情况下,App 组件只渲染一次,所以写错了地方,所以你写的 useEffect 不会在你输入的每个路由中都发生。