如何清除卸载时自动重启功能的超时?

Was*_*ing 2 javascript reactjs react-hooks

我正在使用从服务器获取数据以更新加载日志表的功能。

为此,我将超时设置为15秒,该超时在函数内部调用。我需要在componentWillUnmount上清除此超时,因为它会修改状态,并且我不需要弄乱已卸载组件的状态。

// LogTable is my component
const LogTable = () => {
  let timerId
  const getLoadingData = () => {
    //does something
    timerId = setTimeout(getLoadingData, 15000)
    //more code
  }

  useEffect(() => {
    return function cleanup() {
      clearTimeout(timerId)
    };
  }, []);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,因为timerIduseEffect函数内部未定义,并且我不知道如何解决。

Jon*_*lms 5

您实际上应该将其编写为:

  const useTimeout = (task, time) => useEffect(() => {
    const id = setTimeout(task, time)
    return () => clearTimeout(id);  
 }, []);
Run Code Online (Sandbox Code Playgroud)

然后可以用作:

   useTimeout(10000, () => {
     // ... do whatever
   })
Run Code Online (Sandbox Code Playgroud)

或在您的特定用例中:

  const useInterval = (task, time) => useEffect(() => {
    let id;
    (async function job() {
       await task();
       id = setTimeout(job, time);
    })();
    return () => id && clearTimeout(id);  
 }, []); 

 useInterval(1000, async () => {
   //...
 });
Run Code Online (Sandbox Code Playgroud)