reactjs - React Router NavLink不触发history.listen()函数

标签 reactjs react-router react-ga

我正在尝试使用 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>
)

关于reactjs - React Router NavLink不触发history.listen()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523979/

相关文章:

javascript - ReactJS - 完全相同的元素在 chrome 浏览器中放大/缩小时表现不同

reactjs - 有没有正确的方法在 useEffect 中使用对象作为依赖项?

javascript - 如何从 GTM 代码获取 GA 跟踪 ID

reactjs - 将 Google Analytics 添加到 React

javascript - 您必须向handleSubmit() 传递一个onSubmit 函数,或者将onSubmit 作为prop | 传递。回归形式

javascript - 调用导入类的方法时使用 Async/Await

react-router - component.find ('a).prop(' href')返回undefined而不是href值

javascript - 从使用react-router的web应用程序解析物理URL

javascript - 使用 React Router 重定向显示空白页面