如何在反应中为 setTimeout 创建倒计时数字

How can I create a count down number for setTimeout in react

我正在尝试为撤消按钮创建倒计时数字。

例如:当用户点击邀请按钮邀请另一个用户加入团队时,邀请将从 10 倒计时到 0,如果没有点击撤消按钮,则发送邀请。

这是我的以下代码:

const InviteCard = (props) => {
  const {
    user,
    tab,
    teamId,
    privateTeamId,
    onSubmiteInvitee,
    isInvitationAvailable,
    searchQuery,
    invite,
  } = props;

  async function inviteToTeam(e) {
    if (!user.verifiedDT) {
      notify("User has not verified their identity, can not invite.");
    } else {
      const res = await axios.post("/api/v1/invites/invite", {
        userToInvite: user.public_user_id,
        teamId: teamId,
      });
      if (res.data.inviteWasCreated === false) {
        notify("User has already been invited.");
      } else if (res.data.error !== undefined) {
        notify(res.data.error);
      } else if (res.data.msg) {
        if (res.data.msg === "max members") {
          toggleRequestModal();
          setLimitType("team members");
        }
        if (res.data.msg === "max invites") {
          toggleRequestModal();
          setLimitType("invites");
        }
      } else {
        notify("Invite sent.");
        setWhatToReload("invite data");
        onSubmiteInvitee(e);
      }
    }
  }

 const [sent, setSent] = useState(false);
  const [timeoutId, setTimeoutId] = useState();
  const handleSubmitInvite = (e) => {
    e.preventDefault();
    // call "inviteToTeam" function after 10s
    const id = setTimeout(() => {
      inviteToTeam(e);
    }, 10 * 1000);

    setSent(!sent);
    // save the timer id in the state
    setTimeoutId(id);
  };

  const onUndoClick = (timeoutId) => {
    // get the timeout id from the state
    // and cancel the timeout
    setSent(false);
    clearTimeout(timeoutId);
  };

        {!sent &&
          !isInvitationAvailable(privateTeamId, user.InvitesApplications) && (
            <div>
              <form onSubmit={handleSubmitInvite}>
                <button type="submit" className="invitees-invite-button">
                  Invite
                </button>
              </form>
            </div>
          )}
        {sent && <button onClick={onUndoClick}>Undo</button>}

我怎样才能实现这个功能?我需要使用 lodash 吗??

我认为问题出在函数 onUndoClick 上。您有一个名称为 timeoutId 的状态,但 onUndoClick 函数接受具有相同名称的参数,因此它使用参数的值,并且您从不使用实际状态值,也从不取消超时。尝试:

// parameter removed
const onUndoClick = () => {
    // get the timeout id from the state
    // and cancel the timeout
    setSent(false);
    clearTimeout(timeoutId);
  };
 const [count, setCount] = useState(10);

 const handleSubmitInvite = () => {
    const interval = setInterval(() => {
      setCount((currentCount) => --currentCount);
    }, 1000);
    //execute your function
    if (count === 0) {your fuction};

    // cleanup
    return () => clearInterval(interval);
 }

 const onUndoClick = () => {
   setSent(false);
 };