Error using useeffect and useref TypeError: Cannot read property 'getBoundingClientRect' of null

Error using useeffect and useref TypeError: Cannot read property 'getBoundingClientRect' of null

您好,我的 useref 有问题我的应用程序一直在从我不再访问的页面读取代码

const LandingPage = () => {
    useEffect(() => {
        document.addEventListener("scroll", () => {
            if (window.scrollY < (window.pageYOffset + divRef1.current.getBoundingClientRect().bottom)) {
                onHeaderColorSwitch('#c8e9e6')
                console.log('green')
            } else if (window.scrollY >= (window.pageYOffset + divRef2.current.getBoundingClientRect().top) && window.scrollY < (window.pageYOffset + divRef2.current.getBoundingClientRect().bottom)) {
                onHeaderColorSwitch('#ffae5a')
            } else if (window.scrollY >= (window.pageYOffset + divRef3.current.getBoundingClientRect().top) && window.scrollY < (window.pageYOffset + divRef3.current.getBoundingClientRect().bottom)) {


            }
        })
    }, [])
}

我有这个代码,但是当我使用这个代码切换到联系页面时

function App() {
  
  let routes =<Switch>

   <Route path="/" exact component={landingPage}/>
   <Route path="/contact" exact component={contactPage}/>
  
  </Switch>

然后当我尝试在新页面上滚动时,我收到此错误代码

TypeError: Cannot read property 'getBoundingClientRect' of null
HTMLDocument.<anonymous>
my-app/src/screens/landingPage.js:22
  19 | 
  20 | useEffect(() => {
  21 |     document.addEventListener("scroll", () => {
> 22 |         if (window.scrollY < (window.pageYOffset + divRef1.current.getBoundingClientRect().bottom)) {
     | ^  23 |             onHeaderColorSwitch('#c8e9e6')
  24 | 
  25 |         } else if (window.scrollY >= (window.pageYOffset + divRef2.current.getBoundingClientRect().top) &&  window.scrollY < (window.pageYOffset + divRef2.current.getBoundingClientRect().bottom)) {

即使我现在在新页面上,事件侦听器仍在侦听。 刷新页面后,该错误不会影响我现在和将来如何防止这种情况发生?

您需要在 useEffect 回调函数中移除监听器:

useEffect(() => {
  const listener = () => {
     if (window.scrollY < (window.pageYOffset + divRef1.current.getBoundingClientRect().bottom)) {
         onHeaderColorSwitch('#c8e9e6')
         console.log('green')
     } else if (window.scrollY >= (window.pageYOffset + divRef2.current.getBoundingClientRect().top) &&  window.scrollY < (window.pageYOffset + divRef2.current.getBoundingClientRect().bottom)) {
         onHeaderColorSwitch('#ffae5a')
     } else if (window.scrollY >= (window.pageYOffset + divRef3.current.getBoundingClientRect().top) &&  window.scrollY < (window.pageYOffset + divRef3.current.getBoundingClientRect().bottom)) {
     }
  }
  document.addEventListener("scroll", listener);
  return () => {
    // Clean up the subscription
    document.removeEventListener(listener);
  };
}, []);

Here你会找到更详细的解释。