如何解决如何在nextjs中监听页面变化
我想重用我在 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'来解决这个问题吗?怎么样?
谢谢;)
解决方法
它是这样工作的:
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)
}
},[])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。