因此,我们有这个简单的 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:
它返回一个唯一标识该间隔的间隔 ID,因此
您可以稍后通过调用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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)