如何在事件监听器中读取状态?

时间:2019-04-24 08:48:44

标签: reactjs

我有以下代码:

//...
    const [ scale, setScale ] = useState(0.5);

    const [ altPressed, setAltPressed ] = useState(false);

    const handleScroll = ({ deltaY }) => {
        if (altPressed) {
            const newScale = scale + deltaY;

            setScale(newScale);
        }
    };

    const handleKeyPress = ({ altKey }) => {
        if (altKey) {
            setAltPressed(true);
        }
    };

    const handleKeyRelease = ({ altKey }) => {
        if (!altKey) {
            setAltPressed(false);
        }
    };

    useEffect(() => {
        window.addEventListener("wheel", handleScroll);
        window.addEventListener("keydown", handleKeyPress);
        window.addEventListener("keyup", handleKeyRelease);
    }, []);
//...

但是不幸的是,handleScroll总是读取altPressed的初始状态,即使键盘事件侦听器工作正常,并且它的状态正确,该初始状态也是错误的。

如何解决此问题,使其始终读取最新状态?

1 个答案:

答案 0 :(得分:1)

一种解决方法是使效果取决于altPressed,以便在事件监听器发生更改时重新创建它。您还必须确保从给useEffect的函数返回的函数中删除事件侦听器,以免收到重复的侦听器或内存泄漏。

useEffect(() => {
  window.addEventListener("wheel", handleScroll);
  window.addEventListener("keydown", handleKeyPress);
  window.addEventListener("keyup", handleKeyRelease);

  return () => {
    window.removeEventListener("wheel", handleScroll);
    window.removeEventListener("keydown", handleKeyPress);
    window.removeEventListener("keyup", handleKeyRelease);
  };
}, [altPressed]);