我已经在我的项目中使用了Countdown,它就像一个护身符。但当我将它与简单的输入结合使用时,每当我的输入发生变化时,它就会重新启动。我只想重启它,而且只有在超时的情况下。下面是我的代码:
import React from 'react';
import { Input } from 'reactstrap';
import Countdown from 'react-countdown-now';
import { connect } from 'react-redux';
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = {
code: '',
disabled: false,
};
this.update = this.update.bind(this);
}
update(e) {
this.setState({ code: e.target.value });
}
render() {
return (
<div>
<Input
className="text-center activationCode__letter-spacing"
maxLength="4"
type="text"
pattern="\d*"
id="activationCode__input-fourth"
bsSize="lg"
value={this.state.code}
onChange={this.update}
/>{' '}
<Countdown date={Date.now() + 120000} renderer={renderer} />
</div>
);
}
}
const renderer = ({ minutes, seconds, completed }) => {
if (completed) {
return <p>reset</p>;
}
return (
<p>
{minutes}:{seconds}
</p>
);
};
const mapStateToProps = state => ({
user: state.auth,
});
export default connect(
mapStateToProps,
null,
)(Foo);有什么建议吗?
发布于 2019-06-09 19:30:28
计数器重新启动的原因是,当您更改输入字段时,您正在更新状态。更新状态将导致最终再次执行Date.now()函数的重现器。
你的问题的一个解决方案是在构造函数中将倒计时的日期向上移动,这样它只设置一次,然后在呈现函数中通过state引用它。
constructor(props) {
super(props);
this.state = {
code: '',
disabled: false,
date: Date.now() + 120000
};
this.update = this.update.bind(this);
}
...
render() {
return (
<div>
<Input
className="text-center activationCode__letter-spacing"
maxLength="4"
type="text"
pattern="\d*"
id="activationCode__input-fourth"
bsSize="lg"
value={this.state.code}
onChange={this.update}
/>{' '}
<Countdown date={this.state.date} renderer={renderer} />
</div>
);
}https://stackoverflow.com/questions/56514128
复制相似问题