我正在尝试使用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;
当我在整个应用程序中单击NavLink时,路径会更改并加载相应的组件,但history.listen()函数永远不会触发.但是,如果我使用浏览器的后退/前进功能,它就会触发.
<NavLink to="/account" activeClassName="active">ACCOUNT</NavLink>
如何监听NavLink触发的路由更改?
编辑:进一步的讨论在这里:https://github.com/react-ga/react-ga/issues/122#issuecomment-316427527
最佳答案 使用
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>
)