zoukankan      html  css  js  c++  java
  • react hooks 中使用 addEventListener 监听事件无法访问到最新的 state 的问题

    示例:

    const Exposure = (props: IExposure) => {
      const [hasAsyncData, SetHasAsyncData] = useState(false);
    
      useEffect(() => {
        if (props.asyncData) {
          SetHasAsyncData(true);
        }
      }, [props.asyncData]);
    
      useEffect(() => {
        window.addEventListener("touchmove", handleMove, false);
        window.addEventListener("scroll", handleMove, false);
        return () => {
          window.removeEventListener("touchmove", handleMove);
          window.removeEventListener("scroll", handleMove);
        };
      }, []);
    
      function handleMove() {
        console.log(hasAsyncData);
      }
      return <div ref={measuredRef}></div>;
    };
    
    export default Exposure;
    

    如上述代码所示,props.asyncData 变化之后 hasAsyncData 设置为 true,然后滚动页面,handleMove 中的 hasAsyncData 仍然为初始值 false。
    所以这时要在 hasAsyncData 变化后,重新绑定 addEventListener 事件

    const Exposure = (props: IExposure) => {
      const [hasAsyncData, SetHasAsyncData] = useState(false);
    
      useEffect(() => {
        if (props.asyncData) {
          SetHasAsyncData(true);
        }
      }, [props.asyncData]);
    
      useEffect(() => {
        window.addEventListener("touchmove", handleMove, false);
        window.addEventListener("scroll", handleMove, false);
        return () => {
          window.removeEventListener("touchmove", handleMove);
          window.removeEventListener("scroll", handleMove);
        };
      }, [hasAsyncData]); //改动了这里
    
      function handleMove() {
        console.log(hasAsyncData);
      }
      return <div ref={measuredRef}></div>;
    };
    
    export default Exposure;
    
  • 相关阅读:
    【强烈推荐】 超漂亮的仿腾讯弹出层效果(兼容主流浏览器<转>;
    必须掌握的八个【cmd 命令行】
    grep命令的用法
    sed 命令的用法1
    Paste命令的用法
    uniq命令的用法
    join命令的用法
    Sort命令的用法
    cut命令的用法
    tr命令学习
  • 原文地址:https://www.cnblogs.com/xiaozhumaopao/p/14452589.html
Copyright © 2011-2022 走看看