作者:墮天使love蘇蘇_709 | 来源:互联网 | 2022-12-02 17:28
在我的react
应用程序中,我有一些页面:
主要
服务
联系
个人资料(私人)
等等..
我需要跟踪用户使用Google Analytics(分析)的活动。我用google搜索了react-ga,一切都很好。但是,有了这个库,我必须在使用的每条路线上初始化我的GA。例如:
路线“ /”-主页:
class Main extends Component {
componentDidMount() {
initGA();
}
render() {
return (
)
}
}
我的initGA()
样子是:
import ReactGA from 'react-ga';
export const initGA = () => {
ReactGA.initialize('UA-00000000-1');
ReactGA.pageview(window.location.pathname + window.location.search);
console.log(window.location.pathname + window.location.search);
}
我的App class
样子是:
class App extends Component {
render() {
return (
);
}
}
在我的使用方式中,react-ga
我initGA()
在路由响应上呈现的每个组件上添加功能。我认为initGA()
在每个组件中重复都是不正确的。拜托,伙计们,您如何使用react-ga
?什么是使用react-ga的正确方法?
1> Nastro..:
要使其工作,需要使用Router
功能。因此在App组件中import { Router } from 'react-router-dom'
。它必须是路由器而不是BrowserRouter。
然后 import createHistory from 'history/createBrowserHistory'
const history = createHistory()
ReactGA.initialize('UA-000000-1');
history.listen((location, action) => {
ReactGA.pageview(location.pathname + location.search);
console.log(location.pathname)
});
此代码将在每次更改路线时触发!
比给路由器组件一个历史属性。
完整的代码:
import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory'
import Main from './components/pages/Main';
import ReactGA from 'react-ga';
const history = createHistory()
ReactGA.initialize('UA-00000000-1');
history.listen((location, action) => {
ReactGA.pageview(location.pathname + location.search);
console.log(location.pathname)
});
class App extends Component {
render() {
return (
);
}
}
export default App;