单击按钮后,useState计数器闪烁

时间:2020-10-30 00:06:05

标签: reactjs react-hooks

export const App2 =()=>{
     const [counter,setCounter]=useState(0)
     setTimeout(()=>setCounter(counter+1),1000)

  
     return(
         <div> {counter}
             <button onClick={()=>{setCounter(counter+1)}}> Plus</button>
         </div>

     )



 }

我录制了视频并将其上传到youtube。我不知道为什么会发生这种不稳定情况,并且切换制表符使其又恢复了正常。有人启发吗?我刚刚对this代码进行了修改

1 个答案:

答案 0 :(得分:1)

setTimeout会产生效果,因此我们应该将其放在useEffect()挂钩中。另外,由于setCounter依赖于先前的计数器状态,因此我们可以将一个更新程序函数传递给setCounter,以接收先前的状态值。

import React, { useCallback, useEffect } from "react";

export const App2 = () => {
  const [counter, setCounter] = useState(0);

  const increment = useCallback(() => {
    setCounter((counter) => counter + 1);
  }, []);

  useEffect(() => {
    const id = setTimeout(increment, 1000);
    return () => clearTimeout(id);
  }, [increment]);

  return (
    <div>
      {" "}
      {counter}
      <button onClick={increment}> Plus</button>
    </div>
  );
};