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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM