reactjs – React Router NavLink不触发history.listen()函数
发布时间:2020-12-15 09:36:14 所属栏目:百科 来源:网络整理
导读:我正在尝试使用react-ga库来实施Google Analytics,该库需要在路由更改时触发.我在App.js中有以下设置: import createBrowserHistory from 'history/createBrowserHistory';...const history = createBrowserHistory();history.listen((location) = { consol
我正在尝试使用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> ) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |