在我的react
应用程序中,我有一些页面:
- 主页
- 服务
- 联系我们
- 个人资料(私人)
- 等等。
我需要使用Google Analytics跟踪用户的活动。我搜索了react-ga,这个库很好用。但是,我必须在使用每个路由时初始化我的GA。例如:
路由“ / ”-主页:
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 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>
);
}
}
在我的使用方式中,每当路由响应时,我都会在每个组件上添加initGA()
函数来使用react-ga
。我认为在每个组件中重复initGA()
并不正确。请问大家如何使用react-ga
?使用react-ga
的正确方法是什么?
useEffect
只会被调用一次! - Hafiz TemuribrowserHistory.listen
事件监听器中记录。 - slinden