我想重用我在 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'来解决这个问题吗?怎么样?
谢谢;)
答案 0 :(得分:2)
它是这样工作的:
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)
}
}, [])