因此,我们有了这个简单的 React 组件,它从父组件接收一个整数。单击按钮时,我们会在屏幕上显示整数并开始倒计时。
问题是我怎样才能停止倒计时。在阅读其他 SO 帖子时,我发现了 clearInterval(),但似乎我在这里遗漏了一些东西。
如有任何帮助,我们将不胜感激。如果有人好心向我解释为什么示例代码没有按预期工作,将获得奖励积分。
import React from "react";
export default class TestInterval extends React.Component {
constructor(props) {
super(props);
this.state = {
countDown: this.props.countDown, // An integer from father component
}
}
timer = () => {
setInterval(() => {
if (this.state.countDown === 0) {
this.stopCountDown();
}
this.setState( prevState => ({
countDown: prevState.countDown - 1,
}));
}, 1000)
}
startCountDown = () => {
this.timer();
}
stopCountDown = () => {
clearInterval(this.timer); // Not working
}
render () {
return (
<div>
<button onClick={this.startCountDown}>
Start Countdown
</button>
<p>{this.state.countDown}</p>
</div>
);
}
}
最佳答案
您需要存储从 setInterval
返回的间隔引用。
来自docs :
It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
所以你的代码应该看起来像这样:
this.interval = setInterval(() => {...
然后清除它:
clearInterval(this.interval);
我会在状态真正设置后检查条件(setState
是异步的),您可以在 setState
的回调中执行此操作。
this.interval = setInterval(() => {
this.setState(prevState => ({
countDown: prevState.countDown - 1,
}), () => {
if (this.state.countDown === 0) {
this.stopCountDown();
}
});
}, 1000)
运行示例:
class TestInterval extends React.Component {
constructor(props) {
super(props);
this.state = {
countDown: this.props.countDown, // An integer from father component
}
}
timer = () => {
this.interval = setInterval(() => {
this.setState(prevState => ({
countDown: prevState.countDown - 1,
}), () => {
if (this.state.countDown === 0) {
this.stopCountDown();
}
});
}, 1000)
}
startCountDown = () => {
this.timer();
}
stopCountDown = () => {
clearInterval(this.interval); // Not working
}
render() {
return (
<div>
<button onClick={this.startCountDown}>
Start Countdown
</button>
<p>{this.state.countDown}</p>
</div>
);
}
}
ReactDOM.render(<TestInterval countDown={3} />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - React 类中的清除间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47254124/