[英]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 吗?
我认为问题出在 function onUndoClick
。 您有一个名为 timeoutId 的timeoutId
,但是onUndoClick
function 接受同名的参数,因此它使用参数的值,并且您从不使用实际的 Z9ED39E2EA931586B6A985A6942EF5 值并且永远不会取消 timeoutEZEF5 值尝试:
// 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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.