我设置了一个简单的计时器,每 1 秒计数减少 1 次,一旦计数达到零,最终将停止减少,目前计时器工作正常,但在达到零后会继续减少。 有人可以告诉我有什么问题吗?
我也不确定我是否正确使用componentWillUnmount()
生命周期。
代码如下:
import React, { Component } from "react";
class Timer extends Component {
constructor(props) {
super(props);
this.state = {
count: 10
};
}
render() {
const { count } = this.state;
return <h1>Count:{count} </h1>;
}
componentDidMount() {
this.myTimer = setInterval(() => {
this.setState({
count: this.state.count - 1
});
}, 1000);
}
componentWillUnmount() {
if (this.state.count === 0) {
clearInterval(this.myTimer);
}
}
}
export default Timer;
首先,您将 setState 函数与 prevState 一起使用,因为您从当前状态计算下一个状态,因此您应该更改该部分。
并且您应该自己停止计时器,因为关闭页面时组件会卸载,因此您应该像这样更新 setState 方法
this.myTimer = setInterval(() => {
if (this.state.count > 0) {
this.setState(prevState => ({
count: prevState.count - 1
}));
}
}, 1000);
和componentWillUnmount
方法
componentWillUnmount() {
if (this.myTimer) {
clearInterval(this.myTimer);
}
}
希望这有帮助。