react-router-dom V4.3.1 如何知道我的页面/位置更改事件 [英] How to know my page/location change event in react-router-dom V4.3.1

查看:25
本文介绍了react-router-dom V4.3.1 如何知道我的页面/位置更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

您可以使用 history.listen:

import React, { useEffect } from 'react'从 '../routes/history' 导入历史记录导出默认函数 App() {useEffect(() => {//监听当前位置的变化.const unlisten = history.listen((location, action) => {//location 是一个类似于 window.location 的对象控制台.日志(`当前 URL 是 ${location.pathname}${location.search}${location.hash}`)console.log(`最后一个导航操作是 ${action}`)})返回函数清理(){//要停止监听,调用从 listen() 返回的函数.不听()}}, [])返回 (<div>你好,世界!{/* <MyRoutes/>*/}

)}

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

您可以使用withRouter HOC,或 createBrowserHistory() 来自 history 包,如果使用 Router.对于使用 react-router v5 的用户,useHistory 钩子也可以用来获取历史对象.

如果您使用的是 16.8 之前的 react 版本,您可以使用 componentDidMountcomponentWillUnmount 而不是 useEffects.

I am using react-router-dom V4.3.1. I would like to implement web analytics to my react application on every page/location change. Can you please provide any solution?

解决方案

You can listen to current location changes using 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>
  )
}

There are various ways to get access to history object depending on your react-router version or routing setup.

You can use withRouter HOC, or createBrowserHistory() from history package if have setup routes using Router. For those using react-router v5, useHistory hook can also be used to get history object.

If you are using react version prior to 16.8, you can use componentDidMount and componentWillUnmount instead of useEffects.

这篇关于react-router-dom V4.3.1 如何知道我的页面/位置更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆