要使其工作,需要使用
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 ( <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;


