首页 > 解决方案 > 如何将 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'));

标签: reactjsgoogle-analyticsreact-router

解决方案


演示项目中提供的示例代码也使用了 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);
      }
    }

推荐阅读