我正在尝试将Hotjar库集成到我们的React SPA中以跟踪用户的热图。

我已经遵循了一般教程,但是无法正常工作。

我在文档的元素中有标准的Hotjar跟踪代码。

我正在使用一个高阶组件来连接到React路由器,并试图同时调用window.hj('stateChange',page)和window.hj('vpv',page),但是这些都没有记录在Hotjar热图中。

这是HOC的代码:

import React, { Component } from 'react';
import GoogleAnalytics from 'react-ga';

GoogleAnalytics.initialize(process.env.REACT_APP_GA_TRACKING_ID);

const withPageViewTracker = (WrappedComponent, options = {}) => {
  const trackPage = page => {
    console.log('window.hj', window.hj);
    console.log('page', page);
    // window.hj('stateChange', page);
    window.hj('vpv', page);
  };

  const HOC = class extends Component {
    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);
      }
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };

  return HOC;
};

export default withPageViewTracker;

这是我如何使用HOC:
<Route exact path="/" component={withPageViewTracker(Welcome)} />

最佳答案

您可以使用react hotjar
https://www.npmjs.com/package/react-hotjar

您可以将hotjar注入(inject)组件中任何需要的位置

确保在安装组件后使用它

componentDidMount() {
    hotjar.initialize('xxxxxxx', x);
  }

如果使用钩子(Hook),则可以在没有任何依赖项数组的情况下使用useEffect
const SampleComponent = () => {
  useEffect(() => {
    hotjar.initialize('xxxxxxx', x);
  }, [])

确保在完成所有异步工作后加载hotjar,这样它将记录您想要的所有事件
async componentDidMount() {
        await load1();
        await load2();
        hotjar.initialize('xxxxxxx', x);
}

09-06 08:10