如何在React中使用Google Analytics(分析)? [英] How to use Google Analytics with React?
问题描述
在我的react
应用中,我有一些页面:
In my react
app I have some pages:
- 主要
- 服务
- 联系
- 个人资料(私人)
- 等.
我需要跟踪用户使用Google Analytics(分析)的活动.我用 react-ga 进行了搜索,就很好了.但是,有了这个库,我必须在我使用的每条路线上初始化我的GA.例如:
I need to track users activity with Google Analytics. I googled react-ga and it's just fine. But with this library I have to initialize my GA on every route I use. For example:
"/"路线-主页:
class Main extends Component {
componentDidMount() {
initGA();
}
render() {
return (
<div>
<Component1 />
<Component2 />
</div>
)
}
}
我的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 (
<BrowserRouter>
<div className="App">
<Switch>
<Route exact path="/" component={Main} />
<Route exact path="/signup" component={SignupLayout} />
<Route component={PublicLayout} />
</Switch>
</div>
</BrowserRouter>
);
}
}
在使用react-ga
的方式中,我在每个在路径响应上呈现的组件上添加initGA()
函数.我认为在每个组件中复制initGA()
是不正确的.拜托,伙计们,您如何使用react-ga
?什么是使用react-ga的正确方法?
In my way of using react-ga
I'm adding initGA()
function on every component which renders on route response. I think it is not right to duplicate initGA()
in every component. Please, guys, how do you use react-ga
? What is right way to use react-ga?
推荐答案
要使其正常工作,需要使用Router
功能.
因此,在App组件import { Router } from 'react-router-dom'
中.它必须是路由器而不是BrowserRouter.
To make it work need to use Router
functionality.
So in App component import { Router } from 'react-router-dom'
. It has to be Router not 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)
});
此代码将在每次更改路线时触发!
This code will fire on every route change!
不给路由器组件一个历史记录属性.
Than give a history attribute to your Router component.
完整代码:
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 (
<Router history={history}>
<div className="App">
<Switch>
<Route exact path="/" component={Main} />
<Route exact path="/signup" component={SignupLayout} />
<Route component={PublicLayout} />
</Switch>
</div>
</Router>
);
}
}
export default App;
这篇关于如何在React中使用Google Analytics(分析)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!