簡體   English   中英

如何使用 Google Analytics 設置 Reactjs?

[英]How to setup Reactjs with Google Analytics?

我正試圖讓 GA 跟蹤我所有被 React Router v4 更改的頁面。

我使用庫看到了這段代碼:react-ga

history.listen(location => {
// ReactGA.set({ page: location.pathname })
// ReactGA.pageview(location.pathname)
})

但我認為這不會記錄第一頁。

我看到了這個,但我不知道如何在我的網站上設置它

https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker

我的 index.js 看起來像這樣

ReactDOM.render(

    <Provider routingStore={routingStore} domainStores={DomainStores} uiStores={uiStores}>
      <Router history={history}>
        <ErrorBoundary FallbackComponent={ErrorFallbackComponent}>
        <StripeProvider apiKey={stripeKey}>
          <AppContainer />
          </StripeProvider>
        </ErrorBoundary>
      </Router>
    </Provider>
  ,
  document.getElementById('app')
);

然后在“appConainter”里面我有“Switch”,里面有我的路線

  <Switch>

          <Route
            exact
            path="n"
            component={}
          />
  </Switch>

您需要將它包含在您的AppContainer組件中:

import withTracker from './withTracker'這是您手動創建的文件。

然后創建名為withTracker.jsx的文件並將這些內容放入其中:

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

GoogleAnalytics.initialize("UA-0000000-0");

const withTracker = (WrappedComponent, options = {}) => {
  const trackPage = page => {
    GoogleAnalytics.set({
      page,
      ...options,
    });
    GoogleAnalytics.pageview(page);
  };

  // eslint-disable-next-line
  const HOC = class extends Component {
    componentDidMount() {
      // eslint-disable-next-line
      const page = this.props.location.pathname + this.props.location.search;
      trackPage(page);
    }

    componentDidUpdate(prevProps) {
      const currentPage =
        prevProps.location.pathname + prevProps.location.search;
      const nextPage =
        this.props.location.pathname + this.props.location.search;

      if (currentPage !== nextPage) {
        trackPage(nextPage);
      }
    }

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

  return HOC;
};

export default withTracker;

確保你已經安裝了react-ga

然后,在AppContainer中定義了路由的任何地方都需要調用它:

<Route component={withTracker(App, { /* additional attributes */ } )} />

您鏈接的文檔顯示了如何執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM