【问题标题】:NextJS how to use the useEffect hook for detecting classes on page changeNextJS 如何使用 useEffect 钩子来检测页面变化的类
【发布时间】:2022-12-06 18:52:21
【问题描述】:

在我的nextjs-app 中,我有一个Navbar-组件,我在其中使用useEffect-hook 来检查<body>-tag 是否包含一个类:

导航栏.tsx:

const Navbar = () => {
   
   const router = useRouter()

   const [fullWidthBackground, setFullWidthBackground] = useState(false)

   useEffect(() => {
      const isFullWidth = document.body.classList.contains('full-width-hero')
      if (isFullWidth) {
        setFullWidthBackground(true)
      } else {
        setFullWidthBackground(false)
      }
   }, [fullWidthBackground])

}

到目前为止,这似乎有效,但是当我在具有 full-width-hero-class 的路由/页面上并且它们导航到 /-route(页面 -> index.tsx)时,它没有full-width-hero-类,isFullWidth 仍然返回 true - 那么这里发生了什么?

有人可以帮我吗

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    看起来问题在于您仅在首次呈现组件时检查 full-width-hero 类。如果用户导航到没有此类的其他路由,则不会重新运行 useEffect 挂钩,因此不会更新 fullWidthBackground 状态。

    解决此问题的一种方法是将路由器对象添加到 useEffect 挂钩的依赖项数组中。这将导致钩子在路由更改时重新运行,这将允许您再次检查 full-width-hero 类并相应地更新 fullWidthBackground 状态。

    这是它的样子:

    const Navbar = () => {
       const router = useRouter()
    
       const [fullWidthBackground, setFullWidthBackground] = useState(false)
    
       useEffect(() => {
          const isFullWidth = document.body.classList.contains('full-width-hero')
          if (isFullWidth) {
            setFullWidthBackground(true)
          } else {
            setFullWidthBackground(false)
          }
       }, [fullWidthBackground, router]) // Add router to the array of dependencies
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-08
      • 2021-04-29
      • 2020-09-14
      • 2021-09-10
      • 2019-11-27
      • 2022-11-27
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      相关资源
      最近更新 更多