在我的功能组件中,我使用useState钩子存储状态。每当用户到达页面底部时,我都想添加内容。所以我在useEffect挂钩中的'scroll'上添加了一个EventListener。
事情是它在我第一次到达底部时被触发,我的新内容出现并且我的页面长度增加了,所以我可以进一步滚动。但随后,没有任何追加。
使用console.log
,我检查了我的事件是否触发正确,并且是!
提供给事件侦听器的回调函数似乎停留在过去,我的设置器返回的状态与第一次相同!
gameTeasersToShow
函数有12个元素,我知道如果它起作用了,如果我向下滚动一定的时间就会崩溃,因为数组中没有足够的元素。这是一个测试。
function Index ({ gameTeasersToShow }) {
console.log(useScrollToBottomDetec())
const [state, setState] = React.useState([gameTeasersToShow[0], gameTeasersToShow[1], gameTeasersToShow[2]])
function handleScrollEvent (event) {
if (window.innerHeight + window.scrollY >= (document.getElementById('__next').offsetHeight)) {
setState([...state, gameTeasersToShow[state.length]])
}
}
React.useEffect(() => {
window.addEventListener('scroll', handleScrollEvent)
return () => {
window.removeEventListener('scroll', handleScrollEvent)
}
}, [])
return (
<>
{
state.map(item => {
const { title, data } = item
return (
<GameTeasers key={title} title={title} data={data} />
)
})
}
</>
)
}
答案 0 :(得分:1)
你可以尝试吗?
function handleScrollEvent (event) {
if (window.innerHeight + window.scrollY >= (document.getElementById('__next').offsetHeight)) {
setState(oldState => [...oldState, gameTeasersToShow[oldState.length]])
}
}