Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

关于React hooks中useEffect的一个小问题,请教一下,谢谢了

在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萌新,还请各位大佬解惑,谢谢了!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

试试:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...