react-router-dom V4.3.1 如何知道我的页面/位置更改事件

IT技术 reactjs react-router react-router-dom
2021-05-03 08:23:51

我正在使用 react-router-dom V4.3.1。我想在每次页面/位置更改时对我的 React 应用程序实施网络分析。你能提供任何解决方案吗?

2个回答

解决方法如下图:

const invokeMyWebAnalyticProvider = () => {
  //Code to invoke your analytics
}
const invokeWebTracker = () => {
  if(typeof window.localStorage.getItem('currentPage') !== 'undefined'){
    if(window.localStorage.getItem('currentPage') !== window.location.pathname){
      window.localStorage.setItem('currentPage', window.location.pathname);
      invokeMyWebAnalyticProvider();
    }
  }
}
const Router = () => (
  <MainWrapper>
      {invokeWebTracker()}
      <Switch>        
        <Route exact path='/' component={Login} />
        .
        .
        .
      </Switch>    
  </MainWrapper>
);

使用此代码,我可以跟踪 Web Analytics 中的页面/位置更改。但它不能用于事件跟踪。如果需要事件跟踪需要在每个组件中添加代码。

任何人都可以验证此解决方案吗?

您可以使用history.listen收听当前位置的变化

import React, { useEffect } from 'react'
import history from '../routes/history'

export default function App() {

  useEffect(() => {
    // Listen for changes to the current location.
    const unlisten = history.listen((location, action) => {
      // location is an object like window.location
      console.log(
        `The current URL is ${location.pathname}${location.search}${location.hash}`
      )
      console.log(`The last navigation action was ${action}`)
    })
    return function cleanup() {
      // To stop listening, call the function returned from listen().
      unlisten()
    }
  }, [])

  return (
    <div>
      Hello, World!
      {/* <MyRoutes /> */}
    </div>
  )
}

history根据您的react-router版本或路由设置,有多种方法可以访问对象。

您可以使用withRouter特定的,或createBrowserHistory()历史的包,如果有使用设置路线Router对于那些使用 react-router v5 的人,useHistory也可以使用钩子来获取历史对象。

如果您使用的是16.8之前的 react 版本,则可以使用componentDidMountandcomponentWillUnmount代替useEffects.