react使用router进行页面切换,google analytics不会知道你的页面发生了变化。所以要手动让它知道。
安装react-ga
npm install react-ga --save
我在网上看到使用history.listen实现监听页面变化的代码:
import createHistory from 'history/createBrowserHistory'
import { Router, Route } from 'react-router-dom'
const history = createHistory()
history.listen((location, action) => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
<Router history={history}>
<Route exact path="/" component={Home}/>
<Route exact path="/about" component={About}/>
</Router>
但是不管用,history.listen里的函数在页面变化时没有被调用。
在https://github.com/react-ga/react-ga/issues/122看到了下面的实现,works for me。