0

您好,我在使用 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)) {

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

4

1 回答 1

1

您需要在 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);
  };
}, []);

在这里你会找到更详细的解释。

于 2020-11-19T13:01:41.400 回答