简体   繁体   中英

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

In my functional component I'm storing state with useState hook. 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. 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. With console.log I checked if my event was well triggered and it is !

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 !

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. 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]])
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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