簡體   English   中英

如何打破循環 onClick ReactJS

[英]How to break a loop onClick ReactJS

我有一個 function 使用async await()做了一些 animation 。 我想播放/暫停 animation onClick 我使用useState來更新變量,但 function 的行為不像我想要的那樣。 雖然const print ()正在運行並且當我單擊按鈕時,文本會更新,但 function 不會中斷。 在日志中,“play”被打印了 100 次。 我猜是useStateasync導致了一些事情。 我該如何解決這個問題?

const Test= props => {

    const [ButtonText, SetButtonText] = useState("Play");
    const ToggleButtonText = () => {
        if(ButtonText == "Play")          
            SetButtonText("Pause")

        if(ButtonText == "Pause")
            SetButtonText("Play")
    }

    const delay = ms => new Promise(res => setTimeout(res, ms));

    const print= () => {
        for(var i = 0; i < 100; i++)        
        {
            ///
               work
               await delay(1000);
               work
            ///
           console.log(ButtonText);
           
           if(ButtonText == "Pause")
               break ; 

        }
    };
    return (
           <div>
              <div>
                   ///work component///
              </div>
            <button onClick = {() => ToggleButtonText()}> {ButtonText}</button>
           </div>
    )
}

ButtonText被聲明為const - 它不能在功能組件的給定調用中更改其值。

如果沒有更多信息,我將使用 ref 以及 state,以便循環可以查看 ref 是否已更改:

const buttonTextRef = useRef();
// Update the ref to ButtonText every time ButtonText changes:
useEffect(() => {
  buttonTextRef.current = ButtonText;
}, [ButtonText]);
if (buttonTextRef.current === 'Pause') {
  break;
}

另一種方法是將要迭代的索引放入 state 中,而不是循環 100 次,而是重新渲染 100 次,例如,類似於以下內容:

const [printI, setPrintI] = useState(0);
if (printI) {
  // Then we're in the middle of iterating
  // work
  if (printI < 100) {
    setTimeout(() => {
      setPrintI(printI + 1);
    }, 1000);
  } else {
    setPrintI(0);
  }
};

並停止它,調用setPrintI(0)

暫無
暫無

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

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