React Native -19.React Native Timer定时器的使用

前端之家收集整理的这篇文章主要介绍了React Native -19.React Native Timer定时器的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

React Native -19.React Native Timer定时器的使用

背景:React Native Version:0.3.1
语法 ES6

Step1:介绍

RN的定时器就是一个创建方法。并没有像iOS一样的NSTimer类
根据官方提供的文档,定时器有四种形式: • setTimeout,clearTimeout
• setInterval,clearInterval
• setImmediate,clearImmediate
• requestAnimationFrame,cancelAnimationFrame

  • 见名思义:set和request方法是创建。clear是清除,清除必须有.

Step1:使用

  • setTimeout(function,time)

    function:触发的方法
    time:延迟时间 毫秒
    效果:延迟time时间后执行function,

  • setInterval(function,time)

    function:触发的方法
    time:延迟时间 毫秒
    效果:间隔time时间后执行function

  • setImmediate(function,time)

    function:触发的方法
    time:延迟时间 毫秒
    效果:间隔time时间后(立即)执行function,

  • setImmediate此方法会在js代码块之行结束后执行,就在就要发送批量相应数据到原生之前,如过再方法中又掉用了此方法,他会立即呗掉用。而不会再掉用之前等待原生代码

    以上这句话从官网文档翻译过来,等待以后实际验证。

Step2:实战

import React,{Component} from 'react';
import {AppRegistry,StyleSheet,ActivityIndicator} from 'react-native';

class hello extends Component {
  constructor(props:any){
    super(props);
    var timer1=null;
    var timer2=null;
    var timer3=null;
    this.state = {
      animating: true,};
  }

  componentDidMount(){
    this.timer1 = setInterval(
      @H_404_107@()=>{
        this._consolelogshow();
      },2000,);

    this.timer2 = setTimeout(
      @H_404_107@()=>{console.log('setTimeout22222222'); },1000,);

    this.timer3 = setImmediate(
      @H_404_107@()=>{console.log('setImmediate333333');},3000,);
  }

  componentWillUnmount() {
    // 如果存在this.timer,则使用clearTimeout清空。
    // 如果你使用多个timer,那么用多个变量,或者用个数组来保存引用,然后逐个clear
    this.timer1 && clearInterval(this.timer1);
    this.timer2 && clearTimeout(this.timer2);
    this.timer3 && clearImmediate(this.timer3);

  }

  _consolelogshow(){
    console.log('把一个定时器的引用挂在this上11111');
  }

  render(){
    return(
      <ActivityIndicator
        animating={this.state.animating}
        style={[styles.centerting,{height:80}]}
        size="large"/>
    )
  }
}


 var styles = StyleSheet.create({
   centering: {
    alignItems: 'center',justifyContent: 'center',padding: 8,}
 });

AppRegistry.registerComponent@H_404_107@('hello',()=>hello); 

Step3:实战解读

  • componentDidMount 在生命周期组件加载成功后的方法里创建三个定时器。
  • constructor 方法中声明三个定时器变量,方便全局掉用
  • componentWillUnmount 在生命周期组件将要移除的方法里清除定时器。避免crash
原文链接:https://www.f2er.com/react/305784.html

猜你在找的React相关文章