栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

React挂钩-清除超时和间隔的正确方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

React挂钩-清除超时和间隔的正确方法

__

useEffect
每次运行时
useEffect
都会在运行中 返回
函数(首次运行在组件安装上除外)。考虑一下它,因为每次
useEffect
执行新的执行时,旧的执行都会被删除。

这是使用和清除超时或间隔的一种有效方法:

export default function Loading() {        const [showLoading, setShowLoading] = useState(false)     useEffect(        () => {          let timer1 = setTimeout(() => setShowLoading(true), 1000)          // this will clear Timeout when component unmount like in willComponentUnmount          return () => { clearTimeout(timer1)          }        },        [] //useEffect will run only one time//if you pass a value to array, like this [data] than clearTimeout will run every time this value changes (useEffect re-run)      ) return showLoading && <div>I will be visible after ~1000ms</div>}

如果您需要清除超时或间隔时间不在某个地方:

export default function Loading() {        const [showLoading, setShowLoading] = useState(false)     const timerToClearSomewhere = useRef(false) //now you can pass timer to another component     useEffect(        () => {          timerToClearSomewhere.current = setInterval(() => setShowLoading(true), 50000)          return () => { clearInterval(timerToClearSomewhere.current)          }        },        []      )  //here we can imitate clear from somewhere else place  useEffect(() => {    setTimeout(() => clearInterval(timerToClearSomewhere.current), 1000)  }, []) return showLoading ? <div>I will never be visible because interval was cleared</div> : <div>showLoading is false</div>}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/608801.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号