首页 > 解决方案 > 在 React useEffect 中清除 setInterval 之前,表单不可点击

问题描述

复制行为 沙箱演示的沙箱链接

我在一个 React 组件中有一个钩子,我用它作为回答问题的时间倒计时。

React.useEffect(() => {
     const timer = setInterval(() => {
          setTimeLeft((newTimeLeft) => newTimeLeft <= 0 ? 0 : newTimeLeft - 1);
     }, 50);

     return () => {
          if(timeLeft <= 0){
               clearInterval(timer);
          }
     };       
}, []);

我的表格很简单

<form>
     <FormControl>
          <RadioGroup aria-label="trivia" name="trivia" value={choice} onChange={handleUserChoice}>
               {radioOptions}
          </RadioGroup>
          <Button variant="outlined" color="secondary" onClick={checkAnswer}>Check Choice</Button>
     </FormControl>
</form>

radioOptions是构成答案选择的无线电组件列表。

radioOptions = currentQuestion.questionInfo.choices.map((option) => {
     return (
          <FormControlLabel key={option} value={option} control={<Radio />} label={option} />
     )
})

直到倒计时结束并调用 clearInterval 后,表单才可交互。我无法单击以选择选项中的任何单选选项。该按钮起作用并触发其功能。但是在间隔完成之前,单选选项不是交互式的。

标签: javascriptreactjsmaterial-ui

解决方案


因此,这React.useEffect只是重新呈现整个选项,因为选项位于同一类中,因此选项被选中,但一旦状态发生变化(即计数器运行),组件就会重新呈现计数器和选择,看起来好像没有被选中。直接从主要组件运行选择有所帮助,并且它像您预期的那样工作

<div className="App">
  {timeLeft}
  <form>
    <p>Select a maintenance drone:</p>
    {/* <Choices /> */}

    <div>
      <input type="radio" id="huey" name="drone" value="huey" />
      <label htmlFor="huey">Huey</label>
    </div>

    <div>
      <input type="radio" id="dewey" name="drone" value="dewey" />
      <label htmlFor="dewey">Dewey</label>
    </div>

    <div>
      <input type="radio" id="louie" name="drone" value="louie" />
      <label htmlFor="louie">Louie</label>
    </div>
    <button disabled={timeLeft <= 0 ? true : false} onClick={checkChoice}>
      Check Choice
    </button>
  </form>
</div>

推荐阅读