您好,我遇到了 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)) {
即使我现在位于新页面,事件侦听器仍在侦听。一旦刷新页面,该错误就不会影响我,现在和将来如何防止这种情况发生?
慕姐4208626
相关分类