示例:
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 事件
useEffect(() => {
}, [hasAsyncData])文章来源:https://www.toymoban.com/news/detail-810471.html在useEffect中将他监听起来,从新绑定文章来源地址https://www.toymoban.com/news/detail-810471.html
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;
到了这里,关于react hooks 中使用 addEventListener 监听事件无法访问到最新的 state 的问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!