示例:
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 設(shè)置為 true,然后滾動(dòng)頁(yè)面,handleMove 中的 hasAsyncData 仍然為初始值 false。
所以這時(shí)要在 hasAsyncData 變化后,重新綁定 addEventListener 事件
useEffect(() => {
? }, [hasAsyncData])文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-810471.html在useEffect中將他監(jiān)聽(tīng)起來(lái),從新綁定文章來(lái)源地址http://www.zghlxwxcb.cn/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]); //改動(dòng)了這里
function handleMove() {
console.log(hasAsyncData);
}
return <div ref={measuredRef}></div>;
};
export default Exposure;
到了這里,關(guān)于react hooks 中使用 addEventListener 監(jiān)聽(tīng)事件無(wú)法訪問(wèn)到最新的 state 的問(wèn)題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!