I have a stateless component which needs to listen on keyboard event. It adds keydown
listener when the component is mounted and remove it when the component is unmounted. There is a state test
is boolean
value. It is set to true
when the component is mounted. But in the keydown event listener, its value always false
. It looks like the listener doesn't take the state reference. What's wrong with my code?
const { useEffect, useState } = React;
const Comp = () => {
const [test, setTest] = useState(false);
const keyPressHandler = (e) => {
setTest(!test);
console.log(test);
}
useEffect(() => {
setTest(true);
window.addEventListener('keydown', keyPressHandler);
return () => {
window.removeEventListener('keydown', keyPressHandler);
};
}, []);
return (
<div className="test">
hello {test + ""}
</div>
);
};
You can re-run useEffect when test change which will make the listener always have the current value.
useEffect(() => {
setTest(true);
window.addEventListener('keydown', keyPressHandler);
return () => {
window.removeEventListener('keydown', keyPressHandler);
};
}, [test]);
and you should remove the setTest from the useEffect since it will keep changing test to true
whenever you use setTest()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.