首页 > 解决方案 > 如何将 Google Analytics 与 react-router v5 和 StaticRouter 一起使用?

问题描述

我正在尝试按照如何将 Google Analytics 与 React 结合使用中的建议在我的 React SSR 应用程序中添加带有 react-router v5 StaticRouter 的 Google Analytics?. 我知道 createBrowserHistory 不起作用,所以我想我会使用 createMemoryHistory。似乎在 v4 中删除了 createMemoryHistory?我会尝试收听路由更改,但无法弄清楚如何使用 SSR 做到这一点?或者我可以编写一个 HOC 并修复它。但这似乎是一种更清洁、更简单的方法。

现在要实现这样的目标,我该怎么做?

import ReactGA from 'react-ga';
import { createMemoryHistory } from 'history';

ReactGA.initialize('UA-*********-1');


const history = createMemoryHistory();
history.listen(location => {
  console.log('location', location);
  ReactGA.set({ page: location.pathname });
  ReactGA.pageview(location.pathname);
});

function NotFound() {
  return <h1>Oops, nothing here!</h1>;
}

function App() {
  return (
      <Switch>
        {routes.map(({ path, component, isPublic, exact }) => (
          isPublic ?
            <Route
              key={path}
              exact={exact}
              path={path}
              component={component}
              history={history}
            />
            :
            <ProtectedRoute
              isLoggedIn={user}
              key={path}
              path={path}
              component={component}
              exact={exact}
              public={false}
              history={history}
            />
        ))}
        <Route component={NotFound} />
      </Switch>)
  );
}

标签: javascriptreactjsgoogle-analytics

解决方案


推荐阅读