小编MrB*_*r77的帖子

我需要在react函数中clearTimeout吗?

我在函数中使用“setTimout()”,但没有在“useEffect()”中调用该函数,我是否还需要找到清除超时的方法?

const RandomComponent = () =>{

  const [clicked, setClicked] = useState(false);

  const aFunction = () => {
    setTimeout(()=>{
      setClicked(true);
    },1000);
  }

  return (
    <div>
      <button onClick={aFunction}>Click me!</button>
    </div>  
  )

}

Run Code Online (Sandbox Code Playgroud)

像上面的代码,在这种情况下我需要清除超时吗?谢谢

*更新的问题:

const RandomComponent = () =>{

  const [clicked, setClicked] = useState(false);

  const aFunction = (evt) => {
    return setTimeout(()=>{
      setClicked(true);
    },30000);
  }

  useEffect(()=>{
    return ()=>{
      // how to clear setTimeout in 'aFunction' when I unmount this component?
    }
  });

  return (
    <div>
      <button onClick={aFunction}>Click me!</button>
    </div>  
  )

}

Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

6
推荐指数
1
解决办法
3383
查看次数

标签 统计

javascript ×1

react-hooks ×1

reactjs ×1