【问题标题】:how to listen to page changes in nextjsnextjs如何监听页面变化
【发布时间】:2021-04-29 05:49:43
【问题描述】:

我想重用我在 react-router-dom 中制作的菜单,但这次是在 nextjs 中。目标是当我单击菜单内的链接时,将菜单的状态更改为“false”,将 menuName 更改为“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'来解决这个问题吗?怎么样?

谢谢;)

【问题讨论】:

标签: javascript reactjs react-hooks next.js next-router


【解决方案1】:

它是这样工作的:

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)
    }
  }, [])

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 2021-07-07
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多