简体   繁体   English

React state 在开发工具中更新 - 但不是在 JS 中?

[英]React state updating in dev tools - but not in JS?

for some very strange reason the following function does not read the updated react state, even after scrolling for quite a while:由于一些非常奇怪的原因,即使在滚动了很长一段时间后,以下 function 也没有读取更新后的 React state:

  const handleScroll = () => {
    let shouldBeSticky = false
    console.log (window.scrollY)
    if (window.scrollY >= headerSize) {
      console.log ("Should be sticky")
      shouldBeSticky = true
    }
    else {
      console.log ("Shouldn't be sticky")
      shouldBeSticky = false
    }
    console.log ("navsticky is " + navSticky)
    if (shouldBeSticky && !navSticky) setNavSticky (true)
    else if (!shouldBeSticky && navSticky) setNavSticky (false)
  }

Output after scrolling up and down is always: Should be sticky navsticky is false Output 上下滚动后一直是:应该是sticky navsticky是false

The handleScroll is assigned an eventlistener in the useEffect:在 useEffect 中为 handleScroll 分配了一个事件监听器:

  useEffect(() => {
    headerSize = getHeaderSize()
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    }
  }, [])

Many thanks!非常感谢!

the problem did not lie in the state update itself.问题不在于 state 更新本身。 Rather, one "shouldBeSticky" was triggered, the navbar was unmounted from the dom, messing the whole height check up.相反,触发了一个“shouldBeSticky”,导航栏从 dom 中卸载,搞乱了整个高度检查。 The solution was to keep the code as is and rather turn the navbar invisible instead of unmounting it.解决方案是保持代码不变,而不是将导航栏卸载而不是将其隐藏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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