gpt4 book ai didi

javascript - React hooks - 清除超时和间隔的正确方法

转载 作者:可可西里 更新时间:2023-11-01 01:46:32 26 4
gpt4 key购买 nike

我不明白为什么当我使用 setTimeout 函数时,我的 React 组件开始无限运行 console.log。一切正常,但 PC 开始变得非常滞后。有人说超时功能改变了我的状态和重新渲染组件,设置了新的计时器等等。现在我需要了解如何清除它是对的。

export default function Loading() {
// if data fetching is slow, after 1 sec i will show some loading animation
const [showLoading, setShowLoading] = useState(true)
let timer1 = setTimeout(() => setShowLoading(true), 1000)

console.log('this message will render every second')
return 1
}

清除不同版本的代码无助于:

const [showLoading, setShowLoading] = useState(true)
let timer1 = setTimeout(() => setShowLoading(true), 1000)
useEffect(
() => {
return () => {
clearTimeout(timer1)
}
},
[showLoading]
)

最佳答案

useEffect 中定义的 return () => {/*code/* } 函数在每次 useEffect 运行时运行(第一次渲染除外)组件安装)和组件卸载(如果您不再显示组件)。

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

Sandbox example .

import { useState, useEffect } from "react";

const delay = 5;

export default function App() {
const [show, setShow] = useState(false);

useEffect(
() => {
let timer1 = setTimeout(() => setShow(true), delay * 1000);

// this will clear Timeout
// when component unmount like in willComponentUnmount
// and show will not change to true
return () => {
clearTimeout(timer1);
};
},
// useEffect will run only one time with empty []
// if you pass a value to array,
// like this - [data]
// than clearTimeout will run every time
// this value changes (useEffect re-run)
[]
);

return show ? (
<div>show is true, {delay}seconds passed</div>
) : (
<div>show is false, wait {delay}seconds</div>
);
}

如果您需要清除另一个组件中的超时或间隔:

Sandbox example.

import { useState, useEffect, useRef } from "react";

const delay = 1;

export default function App() {
const [counter, setCounter] = useState(0);
const timer = useRef(null); // we can save timer in useRef and pass it to child

useEffect(() => {
// useRef value stored in .current property
timer.current = setInterval(() => setCounter((v) => v + 1), delay * 1000);

// clear on component unmount
return () => {
clearInterval(timer.current);
};
}, []);

return (
<div>
<div>Interval is working, counter is: {counter}</div>
<Child counter={counter} currentTimer={timer.current} />
</div>
);
}

function Child({ counter, currentTimer }) {
// this will clearInterval in parent component after counter gets to 5
useEffect(() => {
if (counter < 5) return;

clearInterval(currentTimer);
}, [counter, currentTimer]);

return null;
}

Article from Dan Abramov .

关于javascript - React hooks - 清除超时和间隔的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53090432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com