reactjs - ReactJs - Countdown reset unexpectedly
问题描述
I've used Countdown on my project and it works like a charm. but when I combined it with simple input, it would be restart whenever my input changes. I want to restart it only and only if time over. Here is my code:
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);
Any suggestion?
解决方案
您的计数器重新启动的原因是因为当您更改输入字段时,您正在更新您的状态。更新状态将导致重新渲染,最终再次执行 Date.now() 函数。
您的问题的解决方案是在构造函数中将倒计时的日期向上移动,因此它只设置一次,然后在您的渲染函数中通过状态引用它。
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>
);
}
推荐阅读
- automata - NFA 到 DFA 的转换混淆?
- javascript - 如何在一个全新的空白页面中呈现 React Route 组件
- dialogflow-es - dialogflow api 中缺少 401 个未经授权的身份验证参数
- java - 如何将具有给定索引的新元素添加到链接列表中?
- excel - Excel公式:左和函数右
- python - 在 python 中进行网页抓取以获取知识
- javascript - 如何使用可以单击的ngFor在对象数组中具有函数
- django - Django:在测试中检查响应的内容类型
- python - 如何根据单词中的频率对字母进行排序?
- django - 通过 .extra() 过滤 Django 对象 选择 lat 和 lng 半径