简体   繁体   English

当由 EventListener 调用时,useState 挂钩设置器仅运行一次

[英]useState hook setter is running only once when called by an EventListener

In my functional component I'm storing state with useState hook.在我的功能组件中,我使用 useState 挂钩存储 state。 Every time my user gets to the bottom of the page, I want to add content.每次我的用户到达页面底部时,我都想添加内容。 So I added an EventListener on 'scroll' inside a useEffect hook.所以我在 useEffect 挂钩内的“滚动”上添加了一个 EventListener。 The thing is it gets triggered the first time I reach the bottom, my new content appears and my page length increase so I can scroll further.问题是它在我第一次到达底部时被触发,我的新内容出现并且我的页面长度增加了,所以我可以进一步滚动。 But then, nothing append.但是,没有 append。 With console.log I checked if my event was well triggered and it is !使用console.log我检查了我的事件是否被很好地触发了,它是!

It seems like the callback function given to the event listener is stuck in the past and my setter returns the same state as the first time !似乎给事件侦听器的回调 function 卡在过去,我的设置器返回与第一次相同的 state !

The gameTeasersToShow function has 12 elements, I know that if it worked It would crash if I scrolled down a certain good amount of time because the array would not contain enough elems. gameTeasersToShow function 有 12 个元素,我知道如果它有效,如果我向下滚动一定的时间会崩溃,因为数组不包含足够的元素。 It's a test.这是一个考验。

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} />
          )
        })
      }
    </>
  )
}

Can you try that?你能试试吗?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM