gpt4 book ai didi

javascript - react 倒计时错误

转载 作者:行者123 更新时间:2023-11-30 15:05:12 25 4
gpt4 key购买 nike

我已经在 React 组件中实现了一个 vanilla js 倒计时,如下所示:

import React, { Component } from 'react';

class CustomCountDown extends Component {
constructor(props) {
super(props);

this.endTime;
this.msLeft;
this.time;
this.hours;
this.mins;
this.element;
}

twoDigits( n ){
return (n <= 9 ? "0" + n : n);
}

updateTimer() {
this.msLeft = this.endTime - (+new Date);
if (this.msLeft < 1000 ) {
element.innerHTML = "countdown's over!";
} else {
this.time = new Date(this.msLeft );
this.hours = this.time.getUTCHours();
this.mins = this.time.getUTCMinutes();
this.element.innerHTML = (this.hours ? this.hours + ':' + this.twoDigits( this.mins ) : this.mins) + ':' + this.twoDigits( this.time.getUTCSeconds() );
setTimeout( this.updateTimer, this.time.getUTCMilliseconds() + 500 );
}
}

countdown( elementName, minutes, seconds ) {
this.element = document.getElementById( elementName );
this.endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
this.updateTimer();
}

componentDidMount() {
this.countdown("count", 1, 30);
}

render() {
return(
<div id="count">
</div>
);
}
}

export default CustomCountDown;

我不明白为什么会出现以下错误:

enter image description here

最佳答案

当您将 this.updateTimer 传递给 setTimeout 时,您失去了上下文,即 this 不再指向您的组件实例。无论哪种方式,您都需要保持上下文:

setTimeout( this.updateTimer.bind(this), this.time.getUTCMilliseconds() + 500 );
setTimeout( () => this.updateTimer(), this.time.getUTCMilliseconds() + 500 );

作为更好的选择,您可以在构造函数中绑定(bind) updateTimer。这不会在每次调用 updateTimer 时都创建新函数:

constructor(props) {
// ...

this.updateTimer = this.updateTimer.bind(this);
}

关于javascript - react 倒计时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45878062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com