使用 useeffect 和 useref 时出错 TypeError:无法读取 null 的属性

您好,我遇到了 userref 问题,我的应用程序不断从我不再访问的页面读取代码


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)) {

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


喵喵时光机
浏览 365回答 1
1回答

慕姐4208626

您需要在 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);  };}, []);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript