如何在nextjs中监听页面更改

w41d8nur  于 2022-11-29  发布在  其他
关注(0)|答案(2)|浏览(309)

我想重用react中的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" })
    })
  })

并将我的组件 Package 为withRouter:

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

不幸的是,它打印:

TypeError: Cannot read property 'listen' of undefined

我应该更好地使用'useRouter'来解决这个问题吗?如何解决?
谢谢您的评分

ssgvzors

ssgvzors1#

它是这样工作的:
Nextjs:路由器事件

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

yqhsw0fo2#

import { useState, useEffect } from "react";
import { Layout, PageLoading } from ".";
import { useRouter } from "next/router";

const LayoutContainer = ({ pageProps, Component, store, setDeviceWidthAction }) => {
  const router = useRouter();
  const [pageLoading, setPageLoading] = useState(true);

  useEffect(() => {
    setDeviceWidthAction(window.innerWidth);
    setPageLoading(false);
  }, []);

  useEffect(() => {
    const handleStart = (url) => {
      setPageLoading(true);
    };

    const handleStop = () => {
      setPageLoading(false);
    };

    router.events.on("routeChangeStart", handleStart);
    router.events.on("routeChangeComplete", handleStop);
    router.events.on("routeChangeError", handleStop);

    return () => {
      router.events.off("routeChangeStart", handleStart);
      router.events.off("routeChangeComplete", handleStop);
      router.events.off("routeChangeError", handleStop);
    };
  }, [router]);

  if (pageLoading) return <PageLoading />;
  return <Layout {...{ pageProps, Component, store, pageLoading }} />;
};

export default LayoutContainer;

相关问题