如何在HashRouter中使用react-ga?

时间:2018-05-11 10:35:06

标签: reactjs google-analytics react-router

我一直在尝试将Google Analytics与我的React App集成,后者使用react-router-dom v4中的HashRouter。但它根本不起作用抱怨:

  

警告:< HashRouter>忽略历史道具。要使用自定义   历史记录,请使用import { Router }代替import { HashRouter as Router }

同样的问题已在Github上发布:HashRouter not responding to History但尚未提供解决方案。

我必须在不使用任何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'));

1 个答案:

答案 0 :(得分:1)

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