簡體   English   中英

如何使用鈎子以固定的時間間隔觸發功能,並且在滿足某些條件時我想清除時間間隔?

[英]How to trigger a function at regular intervals of time using hooks and when certain criteria is met I want to clear the time interval?

我有一個反應組件,它在安裝后定期執行某個任務。 但我想在滿足標准后清除一次間隔。 我怎樣才能做到這一點?

我的代碼

const [totalTime, setTotalTime] = React.useState(10000);

const foo = () => {
      console.log("Here");
  };

React.useEffect(() => {
    const secondInterval = setInterval(() => {
      if (totalTime > 0) setTotalTime(totalTime - 1000);
    }, 1000);
    return () => clearInterval(secondInterval);
  });

React.useEffect(() => {
    let originalInterval;
    if (totalTime > 0)
      originalInterval = setInterval(() => {
        foo();
        console.log(totalTime);
      }, 5000);
    return () => clearInterval(originalInterval);
  }, []);

當我在 10000 毫秒后觀看控制台時,它仍在記錄此處,並且totalTime始終為 10000 毫秒。 我無法弄清楚到底發生了什么。

您可能需要將舊狀態作為參數傳遞給setTotalTime更新程序函數。 您可能還需要將(另一個)狀態變量作為依賴項傳遞給useEffect鈎子,以便在每次狀態變量更改時執行該函數

React.useEffect(() => {
    const secondInterval = setInterval(() => {
      if (totalTime > 0) setTotalTime(totalTime => totalTime - 1000);
    }, 1000);
    return () => clearInterval(secondInterval);
  }, [...]);

取決於你的標准,你所謂的標准,但你可以只使用另一種狀態,然后useEffect對另一種狀態:

const [criteriaIsMet,setCriteriaIsMet] = useState(false);
useEffect(() => { if(criteriaIsMet) {clearInterval(...)} },[criteriaIsMet])

然后在某個地方,當您執行實際的“標准邏輯”時,您只需繼續執行setCriteriaIsMet(true)

你怎么知道上面useEffect的間隔 Id - 你可以再創建一個特殊的狀態來存儲那個 id,你可以在你原來的useEffect設置它

至於為什么你當前的代碼沒有清除間隔是因為當你使用useEffect和空數組作為第二個參數,並在第一個函數參數中返回函數 - 這將在組件卸載時執行

這些只是您實際擁有的眾多選擇之一:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM