reactjs - React 类组件中的“Timer”类型上不存在 this.setinterval
问题描述
我正在尝试使用 reactjs 和 typescript 制作计时器。我的程序中有计时器类组件。我的代码在这里。我想使用myInterval
我应该使用setInterval()
函数来设置计时器的函数。我面临的问题是 this.myInterval。它表明myInterval
Timer 类型上不存在 。请帮助我。
interface IProps {}
interface IState {
minutes: number;
seconds: number;
isOn: boolean;
}
class Timer extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
minutes: 25,
seconds: 0,
isOn: false,
};
this.startTimer = this.startTimer.bind(this);
this.stopTimer = this.stopTimer.bind(this);
this.resetTimer = this.resetTimer.bind(this);
}
startTimer() {
if (this.state.isOn === true) {
return;
}
this.myInterval = () => setInterval(() => {
const { seconds, minutes } = this.state;
if (seconds > 0) {
this.setState(({ seconds }) => ({
seconds: seconds - 1,
}));
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(this.myInterval);
} else {
this.setState(({ minutes }) => ({
minutes: minutes - 1,
seconds: 59,
}));
}
}
}, 1000);
this.setState({ isOn: true });
}
stopTimer() {
clearInterval(this.myInterval);
this.setState({ isOn: false });
}
resetTimer() {
this.stopTimer();
this.setState({
minutes: 25,
seconds: 0,
});
}
解决方案
有两个问题
- 您从未为 myInterval 设置字段,因此 this.myInterval 不存在
- 您将 a 函数调用设置为 myInterval 而不是 setInterval 的返回
这就是您的代码的外观
//myInterval field
myInterval:NodeJS.Timer;
startTimer() {
if (this.state.isOn === true) {
return;
}
//Assign the return value from setInterval to myInterval
this.myInterval = setInterval(() => {
const { seconds, minutes } = this.state;
if (seconds > 0) {
this.setState(({ seconds }) => ({
seconds: seconds - 1,
}));
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(this.myInterval);
} else {
this.setState(({ minutes }) => ({
minutes: minutes - 1,
seconds: 59,
}));
}
}
}, 1000);
this.setState({ isOn: true });
}
推荐阅读
- java - JavaFX/Spring 自定义 onViewChange 方法
- javascript - 使用 JS 检查是否在 IE 11 中启用了 cookie
- c - png 的字节在 C 中被损坏
- python - 使用 Python 输出从一个时期到下一个时期的原始值差异
- c++ - 向量大小的模糊性
- azure - 如何确保一次只运行一个 Azure Function BlobTrigger?
- r - 如何将数字转换为日期?
- qt - CMake 配置并生成 LMMS 错误
- html - 如何在 CSS 中获取视口的大小?
- php - 防止多次点击添加到购物车按钮 - wordpress/woocommerce