javascript - 如何使用钩子定期触发功能,当满足某些条件时,我想清除时间间隔?
问题描述
我有一个反应组件,它在安装后定期执行某个任务。但是我想在满足标准后清除一次间隔。我怎样才能做到这一点?
我的代码
const [totalTime, setTotalTime] = React.useState(10000);
const foo = () => {
console.log("Here");
};
React.useEffect(() => {
const secondInterval = setInterval(() => {
if (totalTime > 0) setTotalTime(totalTime - 1000);
}, 1000);
return () => clearInterval(secondInterval);
});
React.useEffect(() => {
let originalInterval;
if (totalTime > 0)
originalInterval = setInterval(() => {
foo();
console.log(totalTime);
}, 5000);
return () => clearInterval(originalInterval);
}, []);
当我在 10000 毫秒后观看控制台时,它仍在记录此处,并且总时间始终为 10000 毫秒。我无法弄清楚到底发生了什么。
解决方案
您可能需要将旧状态作为参数传递给setTotalTime
更新程序函数。您还可能需要将(另一个)状态变量作为依赖项传递给useEffect
钩子,以便在每次状态变量更改时执行该函数
React.useEffect(() => {
const secondInterval = setInterval(() => {
if (totalTime > 0) setTotalTime(totalTime => totalTime - 1000);
}, 1000);
return () => clearInterval(secondInterval);
}, [...]);
推荐阅读
- javascript - 有没有办法从数组中获取括号,然后将其中的所有元素放入数组中
- python - 使用装饰器作为类来装饰 Python 类
- javascript - TemplateSyntaxError:无法解析剩余部分:来自“${id}”的“${id}”
- python - 边界框的平均精度 (AP)
- terraform - Terraform:无法安装提供程序,与依赖锁定文件中的校验和不匹配
- django-rest-framework - 访问 ViewSet 对象列表以向序列化程序提供额外的上下文
- c - 解析 C 字符串并将部分字符串存储在变量中
- android - 我应该使用带有 1000 个子视图的 NestedHorizalScrollview 吗?
- c# - 带有代码的 Postgres Npgsql 连接池
- google-chrome - Firefox console getElementBy doesn't work