Home > Web Front-end > JS Tutorial > React Native verification code countdown sharing

React Native verification code countdown sharing

小云云
Release: 2018-01-03 13:09:06
Original
2411 people have browsed it

This article mainly shares the React Native verification code countdown tool class for everyone. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

The example in this article shares the specific code of the React Native verification code countdown tool class for your reference. The specific content is as follows

Because I used the timer directly in the past and did not calculate the current time. Every time you exit the program, the timer never runs. This tool class simply solves the bug of the timer not running when the program exits the background. Then, just write the code~~


/**
 * Created by zhuang.haipeng on 2017.9.11
 *
 * 广告倒计时,验证码倒计时工具类
 *
 * 用法: //60 * 1000 为60秒 , 60 * 60 * 100 为60分钟 ...
 * let countdownDate = new Date(new Date().getTime() + 60 * 1000)
 *  CountdownUtil.settimer(countdownDate, (time) => {
 *   Console.log(time) --> {years: 0, days: 0, hours: 0, min: 0, sec: 49, millisec: 0}
 *  }
 *
 *  切记: 在应用工具类的页面退出的时候, 调用CountdownUtil.stop() 清除定时器,以免内存爆了
 */

export default class CountdownUtil {

  /** 定时器 */
  interval = null;

  /**
   * 创建定时器
   *
   */
  static settimer(countdownDate, callbak) {
    this.interval = setInterval(() => {
      let time = this.getDateData(countdownDate)
      callbak && callbak(time)
    }, 1000)
  }


  /**
   * 侄计时计算 --> 通过此方法计算,可以解决应用退出后台的时候,定时器不走
   * @param countdownDate
   * @return {*}
   */
  static getDateData(countdownDate) {
    let diff = (Date.parse(new Date(countdownDate)) - Date.parse(new Date)) / 1000;

    if (diff <= 0) {
     this.stop() // 倒计时为0的时候, 将计时器清除
      return 0;
    }

    const timeLeft = {
      years: 0,
      days: 0,
      hours: 0,
      min: 0,
      sec: 0,
      millisec: 0,
    };

    if (diff >= (365.25 * 86400)) {
      timeLeft.years = Math.floor(diff / (365.25 * 86400));
      diff -= timeLeft.years * 365.25 * 86400;
    }
    if (diff >= 86400) {
      timeLeft.days = Math.floor(diff / 86400);
      diff -= timeLeft.days * 86400;
    }
    if (diff >= 3600) {
      timeLeft.hours = Math.floor(diff / 3600);
      diff -= timeLeft.hours * 3600;
    }
    if (diff >= 60) {
      timeLeft.min = Math.floor(diff / 60);
      diff -= timeLeft.min * 60;
    }
    timeLeft.sec = diff;
    return timeLeft;
  }

  /**
   * 数字补零 --> 例: 00时01分59秒
   * @param num
   * @param length
   * @return {*}
   */
  static leadingZeros(num, length = null) {

    let length_ = length;
    let num_ = num;
    if (length_ === null) {
      length_ = 2;
    }
    num_ = String(num_);
    while (num_.length < length_) {
      num_ = &#39;0&#39; + num_;
    }
    return num_;
  }

  /** 清除定时器 */
  static stop() {
    clearInterval(this.interval);
  }
};
Copy after login

Use callback to pass the converted time countdown. You can print the time object returned by callbak

Here is a simple example of the verification code countdown:

Idea:

1. First set the state machine isSentVerify to default true to send the verification code
2. After clicking, reset the state machine isSentVerify to false to prevent the user from returning Click to send a network request
3. Declare the countdown time (this can only be declared when you click it. If you enter componentDidMount, the timer will start as soon as you enter)
4. Set the countdown time after the request is successful, and judge If time.sec > 0, set the time, otherwise set the text to "Reacquire"
5. Then determine that the text is "Reacquire", and then set the state machine isSentVerify to true, so that the user counts down After finishing, you can send the verification code again.
6. When the network request fails, set isSentVerify to true at the catch point so that the user can obtain the verification code again


 if (this.state.isSentVerify === true) {
      // 倒计时时间
      let countdownDate = new Date(new Date().getTime() + 60 * 1000)
      // 点击之后验证码不能发送网络请求
      this.setState({
        isSentVerify: false
      });

      Api.userRegisterCheckCode(this.state.phoneText)
        .then(
          (data) => { // 倒计时时间
            CountdownUtil.settimer(countdownDate, (time) => {
              this.setState({
                timerTitle: time.sec > 0 ? time.sec + &#39;s&#39; : &#39;重新获取&#39;
              }, () => {
                if (this.state.timerTitle == "重新获取") {
                  this.setState({
                    isSentVerify: true
                  })
                }
              })
            })
          }
        ).catch((err) => {
        this.setState({
          isSentVerify: true,
        })
      });
    }
Copy after login

When exiting the page, remember to destroy it Timer


 componentWillUnmount() {
    CountdownUtil.stop()
  }
Copy after login

Rendering:

##Related recommendations:


Send verification code countdown function when mobile phone registration

Instance analysis of 60s countdown to get verification code in WeChat applet

js countdown to get verification code Implementation method

The above is the detailed content of React Native verification code countdown sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template