javascript - 如何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>
)}
解决方案
您可能希望有一个useEffect
检查 Count 的当前值。所以添加这样的东西:
useEffect(() => {
if (count === 0) {
clearInterval(intervalval)
}
}, [count]);
推荐阅读
- lua - 尝试在 Lua/Love2D 中绘制平台时出错
- node.js - 执行 npm start 时出现 Azure 函数节点错误
- javascript - 从javascript中的异步函数获取返回值
- django - 除非打开 chrome 开发人员工具,否则 React/Redux 应用程序无法工作?
- javascript - InfiniteScroll - 如何重置所有网格?
- css - 是否可以在不同的屏幕中查看页面?
- quill - 如何使 Quill delta 输出变平?
- c++ - 分支定界根节点是否适合使用继承?
- ldap - 在 OpenLDAP 中禁用分页搜索
- ios - SwiftUI 截断某些字母的文本