[英]useState hook setter is running only once when called by an EventListener
在我的功能組件中,我使用 useState 掛鈎存儲 state。 每次我的用戶到達頁面底部時,我都想添加內容。 所以我在 useEffect 掛鈎內的“滾動”上添加了一個 EventListener。 問題是它在我第一次到達底部時被觸發,我的新內容出現並且我的頁面長度增加了,所以我可以進一步滾動。 但是,沒有 append。 使用console.log
我檢查了我的事件是否被很好地觸發了,它是!
似乎給事件偵聽器的回調 function 卡在過去,我的設置器返回與第一次相同的 state !
gameTeasersToShow
function 有 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} />
)
})
}
</>
)
}
你能試試嗎?
function handleScrollEvent (event) {
if (window.innerHeight + window.scrollY >= (document.getElementById('__next').offsetHeight)) {
setState(oldState => [...oldState, gameTeasersToShow[oldState.length]])
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.