nextjs监听页面变化的方法

how to listen to page changes in nextjs

我想重用我在 react-router-dom 中制作的菜单,但这次是在 nextjs 中。目标是当我单击菜单内的 link 时,将菜单状态更改为 'false',将菜单名称更改为 'menu'。

我使用 useEffect 函数来监听历史:

//use effect for page changes
  useEffect(() => {
    //listen for page changes
    history.listen(() => {
      setState({ clicked: false, menuName: "Menu" })
    })
  })

并用 withRouter 包装我的组件:

import { withRouter } from 'next/router'
[...]
export default withRouter(Header);

不幸的是,它打印:

TypeError: Cannot read property 'listen' of undefined

我应该更好地使用 'useRouter' 来解决这个问题吗?怎么样?

谢谢 ;)

它是这样工作的:

Nextjs : Router Events

import { useRouter } from "next/router";

...

const router = useRouter()
  useEffect(() => {
    const handleRouteChange = (url) => {
      console.log(
        `App is changing to ${url}`
      )
      setState({ clicked: false, menuName: "Menu" })
    }

    router.events.on('routeChangeStart', handleRouteChange)

    // If the component is unmounted, unsubscribe
    // from the event with the `off` method:
    return () => {
      router.events.off('routeChangeStart', handleRouteChange)
    }
  }, [])