react-native 定时器
来源:互联网 发布:三菱fx2n 4da编程实例 编辑:程序博客网 时间:2024/06/03 23:07
定时器是一个应用中非常重要的部分。React Native实现了和浏览器一致的定时器Timer
定时器:
- setTimeout, clearTimeout
- setInterval, clearInterval
- setImmediate, clearImmediate
- requestAnimationFrame, cancelAnimationFrame
requestAnimationFrame(fn)和setTimeout(fn, 0)不同,前者会在每帧刷新之后执行一次,而后者则会尽可能快的执行(在iPhone5S上有可能每秒1000次以上)。
setImmediate则会在当前JavaScript执行块结束的时候执行,就在将要发送批量响应数据到原生之前。注意如果你在setImmediate的回调函数中又执行了setImmediate,它会紧接着立刻执行,而不会在调用之前等待原生代码。
Promise的实现就使用了setImmediate来执行异步调用。
切记:无论是哪种,在卸载组件之前一定要清除计时器。
setTimeout( () => { console.log('把一个定时器的引用挂在this上'); }, 500 );上文的代码就是在500毫秒之后打印一句话,
而setInterval是每隔一段时间执行:
setInterval(() => { i++;}, 1000)上文的代码就是每隔1000毫秒使i变成i+1。
看一下使用实例:
componentDidMount() { let i = 2; this.timer = setInterval(() => { self.refs.text.setNativeProps({ style: {opacity: i % 2} }); i++; }, 1000)}
每隔1000毫秒执行个操作,使i+1,并且改变text的透明度。
<Text ref="text" style={{ position: 'absolute', top: 500, left: 50, backgroundColor: 'grey' }}>{this.state.select}</Text>
之后记得卸载定时器:
componentWillUnmount() { // 请注意Un"m"ount的m是小写 // 如果存在this.timer,则使用clearTimeout清空。 // 如果你使用多个timer,那么用多个变量,或者用个数组来保存引用,然后逐个clear this.timer && clearTimeout(this.timer);}
务必在卸载组件前清除定时器!
我们发现很多React Native应用发生致命错误(闪退)是与计时器有关。具体来说,是在某个组件被卸载(unmount)之后,计时器却仍然在运行。要解决这个问题,只需铭记在unmount组件时清除(clearTimeout/clearInterval)所有用到的定时器即可:
componentDidMount() { this.timer = setTimeout( () => { console.log('把一个定时器的引用挂在this上'); }, 500 ); } componentWillUnmount() { // 请注意Un"m"ount的m是小写 // 如果存在this.timer,则使用clearTimeout清空。 // 如果你使用多个timer,那么用多个变量,或者用个数组来保存引用,然后逐个clear this.timer && clearTimeout(this.timer); }
阅读全文
1 0
- react-native 定时器
- react native 定时器的使用
- React Native -19.React Native Timer定时器的使用
- React Native中定时器的使用
- 《React-Native系列》18、 RN之定时器Timer
- React Native 学习笔记二十一(定时器学习)
- 《React-Native系列》18、 RN之定时器Timer
- react-native time定时器 防止内存泄露的注意点
- react native
- React Native
- React Native
- React- Native
- react-native
- React Native
- React Native
- react native
- React Native
- react-native
- equals()与==的区别与实际应用
- Codeforces 816B-Karen and Coffee
- Oracle数据库基础信息查询
- linux服务器的日志管理
- QT中的定时器使用
- react-native 定时器
- HTML:用递归的方法计算1+2+3+4...+10
- Java设计模式(二):工厂方法模式
- 位运算符
- 运算符
- 关于安装python3.x 及常用安装包,如wheel numpy scripy lxml openSSl Scrapy。
- java 基础-集合
- 0023_Merge k Sorted Lists
- 关于MVC和DAO设计模式