簡體   English   中英

使用 useeffect 和 useref TypeError 時出錯:無法讀取 null 的屬性“getBoundingClientRect”

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

在這里你會找到更詳細的解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM