__
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>}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)