javascript - 如何将 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>)
);
}
解决方案
推荐阅读
- java - URL truncated when it contains semicolons
- android - ListView - 使按钮 onClick 事件将值添加到同一行的 EditText
- python - Raspberry Pi 3:OpenCV 3.4.0 安装后缺少一些文件,无法在我的代码中调用
- javascript - 将字母分配给特定范围内的数值
- ldap - LDAP err32 on Jetty JAAS setting with Openldap
- linux - How to Do a For Loop Instead of a While Loop in Shell Scripting
- c - 将 execvp 与输入文件一起使用到程序并将输出重定向到新文件
- .net-core - 添加 nuget 包时出现 Asp.Net Core 错误
- java - 如何在来自servlet的json响应中发送带有一些数据的图像
- laravel - “页面已过期,请刷新并重试。”