react router v4 中监听路由变化,使用google analytics

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);
});


    
    

但是不管用,history.listen里的函数在页面变化时没有被调用。

在https://github.com/react-ga/react-ga/issues/122看到了下面的实现,works for me。

// ...
import ReactGA from 'react-ga';

ReactGA.initialize('UA-000000000-1');

class Analytics extends React.Component> {
  componentDidMount() {
    this.sendPageChange(this.props.location.pathname, this.props.location.search)
  }

  componentDidUpdate(prevProps: RouteComponentProps) {
    if (this.props.location.pathname !== prevProps.location.pathname
      || this.props.location.search !== prevProps.location.search) {
      this.sendPageChange(this.props.location.pathname, this.props.location.search)
    }
  }

  sendPageChange(pathname: string, search: string = "") {
    const page = pathname + search
    ReactGA.set({page});
    ReactGA.pageview(page);
  }

  render() {
    return null
  }
}

const AnalyticsTracker = () => {
  return 
}

// ...further down the file:
      
        
        
          
          // ...

你可能感兴趣的:(react,网站)