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

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

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>}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5614934.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存