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;
    
  • 相关阅读:
    用R语言完成的交通可视化报告
    二维码(带有图片)的生成
    大文件数据去重复
    shell 脚本大文件处理
    Domain-specific language 领域特定语言
    cacheed 限制 4节点 3000万 es 批量删除 shell脚本练习 elasticsearch_action
    cached
    广告中嵌入非广告 非广告中嵌入广告
    js 四种调用方式 Method Invocation Pattern
    js 变量作用域
  • 原文地址:https://www.cnblogs.com/xiaozhumaopao/p/14452589.html
Copyright © 2011-2022 走看看