Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

在useEffect中使用了setInterval,并且指定该effect只执行一次,代码如下,

export default function Effect() {
  const [count, setCount] = useState(0);
  console.log("count in func ", count);

  useEffect(() => {
    const timeId = setInterval(() => {
      console.log("count in interval: ", count);
      setCount(count + 1);
    }, 1000);
    return () => {
      console.log("clear");
      clearInterval(timeId);
    };
  }, []);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

输出如下
image.png

我能理解输出中的前4行以及之后最后一行,可是不明白为什么会有第五行‘count in func 1’的输出出现,这说明它又渲染了一次,不是这时候count值已经为1了吗,那么再次setCount(0 + 1) 为什么还会导致重渲染?
react hooks萌新,还请各位大佬解惑,谢谢了!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

试试:

useEffect(() => {
    const timeId = setInterval(() => {
      console.log("count in interval: ", count);
      setCount(count + 1);
    }, 1000);
    return () => {
      console.log("clear");
      clearInterval(timeId);
    };
  }, [count]); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...