首页 > 解决方案 > 如何setInterval在0时会消失

问题描述

我创建了一个函数,当点击邀请按钮时,setInterval 将从 10 开始倒计时到 0,然后它将邀请发送给用户,但在数字达到 0 后它仍然继续倒计时,但邀请已发送。

这是我的以下代码:

  const [sent, setSent] = useState(false);
  const [timeoutId, setTimeoutId] = useState(null);
  const [count, setCount] = useState(10);
  const [intervalval, setIntervalval] = useState();
  const [anchorEl, setAnchorEl] = useState();

  const handleSubmitInvite = (e) => {
    e.preventDefault();
    // call "inviteToTeam" function after 10s
    const id = setTimeout(() => {
      inviteToTeam(e);
    }, 10 * 1000);
    const interval = setInterval(() => {
      setCount((currentCount) => --currentCount);
    }, 1000);
    if (interval === 0) {
      setSent(false);
    }
    setIntervalval(interval);
    setSent((currentSentValue) => !currentSentValue);
    setTimeoutId(id); // save the timer id in the state
  };

  const onUndoClick = () => {
    clearInterval(intervalval);
    setCount(10);
    setSent((currentSentValue) => !currentSentValue); // get the timeout id from the state and cancel the timeout
    clearTimeout(timeoutId);
  };

{!sent &&
  !isInvitationAvailable(privateTeamId, user.InvitesApplications) &&
  user.verifiedDT !== null && (
    <div>
      <form onSubmit={handleSubmitInvite}>
        <Button type="submit" className={classes.inviteButton}>
          Invite
        </Button>
      </form>
    </div>
  )}

{sent && (
  <Button className={classes.unInviteButton} onClick={onUndoClick}>
    Uninvite {count}
  </Button>
)}

标签: javascriptreactjsreact-hooks

解决方案


您可能希望有一个useEffect检查 Count 的当前值。所以添加这样的东西:

useEffect(() => {
  if (count === 0) {
    clearInterval(intervalval)
  }
}, [count]);

推荐阅读