reactjs - 如何将 react-ga 与 HashRouter 一起使用?
问题描述
我一直在尝试将 Google Analytics 与我的 React 应用程序集成,该应用程序使用 react-router-dom v4 中的 HashRouter。但它根本不起作用抱怨:
警告:<HashRouter> 忽略 history 属性。要使用自定义历史记录,请使用
import { Router }
而不是import { HashRouter as Router }
.
相同的问题已在 Github 上发布:HashRouter not respond to History but no solutions provided yet。
我必须在不使用任何 HOC 的情况下坚持使用 HashRouter 进行项目。这可能吗?
我目前的实现:
ReactGA.initialize('UA-XXXXXXXX-X');
const history = createHistory()
history.listen((location, action) => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
ReactDOM.render((
<HashRouter history={history}>
<Switch>
<Route path="/" name="App" component={App} />
</Switch>
</HashRouter>
),document.getElementById('root'));
解决方案
演示项目中提供的示例代码也使用了 HashRouter。如此处所见; https://github.com/react-ga/react-ga/blob/master/demo/app/Router.jsx
使用 HOC,withTracker,不是必须的。它只是在每个页面上轻松插入跟踪触发器。如果您在自己的页面组件中实现相同的代码,您可以获得相同的结果。
然后,您需要将以下代码添加到您要手动跟踪的每个组件;
const trackPage = (page) => {
ReactGA.set({
page
});
ReactGA.pageview(page);
};
componentDidMount() {
const page = this.props.location.pathname;
trackPage(page);
}
componentWillReceiveProps(nextProps) {
const currentPage = this.props.location.pathname;
const nextPage = nextProps.location.pathname;
if (currentPage !== nextPage) {
trackPage(nextPage);
}
}
推荐阅读
- python - 从 pcap 文件中提取 UDP 数据流
- c++ - 在 Julia 中编写和调用 ArrayFire 的自定义 C 函数的正确方法
- java - 带有 ViewModel、LiveData 和 Room 的 AsyncTask、AsynTaskLoader 或 Executer?
- python - 将嵌入在 Dataframe 中的 Row RDD 转换为 List
- linux-kernel - 释放平台驱动设备结构
- java - 无法将 xml 字符串设置为 jvm 属性
- python -
TypeError:resize_images() 得到了一个意外的关键字参数“preserve_aspect_ratio” - php - 我有五个表,我想在 laravel 中雄辩的 ORM 关系。并使用控制器检索值
- angular - 无法设置未定义的属性“ProjectId”
- python - 获取基于熊猫数据框中另一列的两列的频率计数