[英]why does the component render 3 times?
I have a component like this:我有一个这样的组件:
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
console.log("comp run");
const tick = () => {
setCount(count + 1);
console.log(count);
};
useEffect(() => {
const timer = setInterval(tick, 10000);
console.log("effect run");
return () => {
clearInterval(timer);
console.log("clear func run");
};
}, []);
return <div>{count}</div>;
}
export default Counter;
When the code runs, the console outputs as follows:代码运行时,控制台输出如下:
Output immediately when the program runs:程序运行时立即输出:
comp run
补偿运行
effect run
效果运行
after 10 seconds : 10 秒后:
comp run
补偿运行
0
0
after 10 seconds : 10 秒后:
comp run
补偿运行
0
0
after 10 seconds : 10 秒后:
0 (then it keeps increasing by 0 every ten seconds)
0(然后每十秒增加0)
What I don't understand here is exactly this: "comp run" is printed on the screen 3 times.我在这里不明白的是:“comp run”在屏幕上打印了 3 次。 Why 3 ?
为什么 3 ?
This is because useEffect memoize all values inside it.这是因为useEffect 会记住其中的所有值。 You can use two ways:
您可以使用两种方式:
Add count
to useEffect's dependencies array.将
count
添加到 useEffect 的依赖项数组。 And when count changes, useEffect will refreshed.当计数改变时,useEffect 会刷新。
useEffect(() => { //Your old code here }, [count]); //Here
Create a function inside of useCallback hook and memoize function for better performance.在useCallback钩子和 memoize 函数中创建一个函数以获得更好的性能。 Works like in first way, but dependent by tick fucntion, wich dependent by count state.
像第一种方式一样工作,但取决于刻度功能,取决于计数状态。
const tick = useCallback(() => { setCount(count + 1); console.log(count); }, [count]); useEffect(() => { const timer = setInterval(tick, 1000); console.log("effect run"); return () => { clearInterval(timer); console.log("clear func run"); }; }, [tick]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.