javascript - 如何清除 React 中的间隔
问题描述
我正在通过useState
在 react.js 中使用钩子来构建秒表,但是在实现暂停功能时,我注意到我无法清除间隔。我是新手,我尝试了很多东西,但仍然没有用。如果有人可以帮助我修复代码或建议我以其他方式。
这是我的代码:
function App() {
const [stopwatch, setStopwatch] = useState({
hour: 0,
min: 0,
sec: 0,
secElapsed: 0,
minElapsed: 0,
});
const [buttonState, setButtonState] = useState({
start: true,
stop: false,
pause: false,
resume: false,
});
var interval = null;
function onStart() {
// i want to clear this interval when the onPause function is called
var clrInt = setInterval(() => {
setStopwatch(prevValue => {
prevValue.secElapsed++;
return {
hour: Math.floor(prevValue.secElapsed / 3600),
minElapsed: Math.floor((prevValue.secElapsed + 1) / 60),
min: prevValue.minElapsed % 60,
sec: prevValue.secElapsed % 60,
secElapsed: prevValue.secElapsed,
};
});
}, 1000);
setButtonState(prevValue => {
return {
...prevValue,
start: false,
pause: true,
stop: true,
};
});
interval = clrInt;
}
function onPause() {
setButtonState(prevValue => {
return {
...prevValue,
pause: false,
resume: true,
};
});
// i want to clear the interval in onStart function here
clearInterval(interval);
}
return (
<div>
<h1>
{stopwatch.hour < 10 ? '0' + stopwatch.hour : stopwatch.hour}:
{stopwatch.min < 10 ? '0' + stopwatch.min : stopwatch.min}:
{stopwatch.sec < 10 ? '0' + stopwatch.sec : stopwatch.sec}
</h1>
{buttonState.start ? <button onClick={onStart}>Start</button> : null}
{buttonState.pause ? <button onClick={onPause}>Pause</button> : null}
{buttonState.stop ? <button>Stop</button> : null}
{buttonState.resume ? <button>Resume</button> : null}
</div>
);
}
解决方案
我认为间隔不适合组件的状态。相反,我会使用useRef钩子在组件的整个生命周期中保持它。
无论如何,你开始思考钩子很好:)
一种更简洁的方法是实现类似useInterval的东西:
const [isRunning, setIsRunning] = useState(true)
useInterval(() => {
// Your custom logic here
}, isRunning ? 1000 : null)
const onPause = () => {
// ...
setIsRunning(false)
}
这是一个实际实现钩子的演示。
推荐阅读
- c++ - 为什么 std::min 只支持 initializer_list?
- node.js - 如何在同一个 Node 应用程序的不同端点上创建单独的 PouchDB,并位于磁盘上的不同数据库中?
- sml - 为什么我不能围绕我的 addAll 函数调用简化?
- javascript - AngularJS 没有通过 HTML 链接
- shiny - yaml::yaml.load(..., eval.expr = TRUE) 中的错误:在 Rmarkdown 中使用闪亮时
- c# - 当值是类类型时如何显示字典中的所有值
- javascript - 将具有不同 id 的元素拖放到相应的拖放区中
- c++ - 使用 memcpy 时的 C++(访问冲突写入位置 0xDDDDDDDD)
- redis - How to connect to redislabs in Python
- javascript - 在内容可编辑的 div 中获取插入符号的绝对位置?