4

我正在尝试使用react-ga在路线更改时需要触发的库来实现 Google Analytics。我在 App.js 中有以下设置:

import createBrowserHistory from 'history/createBrowserHistory';
...

const history = createBrowserHistory();
history.listen((location) => {
    console.log('ANALYTICS CODE GOES HERE', location);
});

class App extends Component {
    render() {
        return (
            <Provider store={...}>
                <Router history={history}>
                    ....
                </Router>
            </Provider>
        );
    }
}

export default App;

当我在整个应用程序中单击 a 时NavLink,路线会更改并加载适当的组件,但该history.listen()功能永远不会触发。但是,如果我使用浏览器的后退/前进功能,它会触发。

<NavLink to="/account" activeClassName="active">ACCOUNT</NavLink>

如何收听由 a 触发的路由更改NavLink

编辑:在这里进行进一步讨论:https ://github.com/react-ga/react-ga/issues/122#issuecomment-316427527

4

1 回答 1

1

使用react-router<Route />组件作为跟踪功能的包装器 - 每次位置更改时都会重新渲染路由。例如:

import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import ReactGA from 'react-ga'

ReactGA.initialize('UA-00000000-1')

const tracker = ({location}) => {
  // console.log('tracking', location.pathname)
  ReactGA.set({page: location.pathname})
  ReactGA.pageview(location.pathname)
  return null
}

const App = (props) => (
  <Router>
    <div>
      <Route render={tracker} />
      ...
    </div>
  </Router>
)
于 2017-11-20T23:13:04.947 回答