ReactJs-倒计时意外重置

法赞·纳吉普(Farzan Najipour)

我在项目中使用了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);

有什么建议吗?

斯蒂芬·奥尔森

计数器重新启动的原因是,当您更改输入字段时,您正在更新状态。更新状态将导致重新渲染,最终重新执行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>
  );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章