0

こんにちは、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)) {

新しいページに移動しても、イベント リスナーはまだリッスンしています。ページを更新すると、バグは影響しません。現在および将来、これを防ぐにはどうすればよいですか?

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 に答える