Google Analytics 基本使用
1.注册谷歌分析
https://marketingplatform.google.com/about/
完善个人信息,获取跟踪Id,同意协议。
2.为网站加上谷歌分析代码
https://developers.google.com/analytics/devguides/collection/gtagjs 必须先完成上述操作,才能继续下面的步骤,让你本地的服务能获取谷歌分析的数据。
React 集成 Google Analytics
如果使用的是前端路由(React-router),就需要别的方法。
React 需要使用 React-GA
https://www.npmjs.com/package/react-ga
可以配合 react-router 使用, 使用HOC(High Older Component 高阶组件), https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker
import ReactGA from 'react-ga';
import React, { Component } from 'react';
const GoogleAnalyticsInit = () => {
if (GOOGLE_ANALYTICS_ID) {
ReactGA.initialize(GOOGLE_ANALYTICS_ID);
}
};
GoogleAnalyticsInit();
const withTracker = (WrappedComponent, options = {}) => {
const trackPage = (page) => {
if (GOOGLE_ANALYTICS_ID) {
ReactGA.set({
page,
...options,
});
ReactGA.pageview(page);
}
};
const GoogleAnalytics = class extends Component {
componentDidMount() {
const page = window.location.pathname;
trackPage(page);
}
render() {
return <WrappedComponent {...this.props} />;
}
};
return GoogleAnalytics;
};
export default withTracker;
import { Route } from 'react-router-dom';
import withTracker from 'App/Common/HigherComponents/GoogleAnalyticsRoute';
const AuthRoute = authRoute(Route);
<AuthRoute
auth={Permission.CREATE_JOB}
exact
path="/jobs/new"
component={withTracker(PostJob)}
/>
本地调试
由于墙的原因,google服务无法访问本地数据,我使用
https://ngrok.com/ 将本地端口 转换为 URL 如
http://d7b5fa6f.ngrok.io -> localhost:8080