我正在尝试在网站上实现分段滚动。有一种状态叫做滚动:
const [scroll, setScroll] = useState({ currentSectionIndex: 0 });
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
我尝试更新 handleScroll 中的状态:
const handleScroll = () => {
let currentScrollPosition = window.scrollY
//window.scrollTo(0, yPositions[scroll])
setScroll({ ...scroll, currentSectionIndex: scroll.currentSectionIndex + 1 })
let windowScrolls = window.scrollY;
console.log(scroll)
};
但是currentSectionIndex
滚动时,显示的是默认值0
。为什么?setScroll
应该更新功能组件中的状态。我究竟做错了什么?
再会。
当您根据内容更改状态时,您应该记住它是异步工作的。因此,您不会总是在滚动值中获得您需要的值。在这种情况下,值得使用回调函数来设置状态
它看起来像这样:
在这种情况下,状态将具有正确的值。
所有的代码都会像这样
如果您有任何问题,请提出。祝你好运!