[英]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.