繁体   English   中英

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

[英]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.

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