React Native 编码习惯带来的性能问题
来源:互联网 发布:东北林大网络 编辑:程序博客网 时间:2024/06/06 00:19
React Native 编码习惯带来的性能问题
React中当一个组件的属性发生变化时候,会触发该组件重新 render ,如果组件直接设置 props 为对象或数组,而两个对象或者两个数组比较是比较地址,即使内部数据是一致的,也会认为是不同的数据,组件会认为前后 props 不一致,重新 render 。
问题一:在设置一个组件 props 的时候直接设置对象
<TouchableOpacity onPress={()=>{}}> <Text> 登录 </Text></TouchableOpacity>
这是一个登录按钮,TouchableOpacity 的 onPress 中设置 {()=>{}} ,我们知道 {} === {} 结果是false,同样 funcation {()=>{}} === {()=>{}} 也是false。
解决方案
对于这样props我们可以在成员上使用箭头函数,在 onPress 中调用。
login = () => {} <TouchableOpacity onPress={this.login}> <Text> 登录 </Text></TouchableOpacity>
对于有些方法需要传参数,我们则可以采用 bind 的方式。
对于某些props已经带参数返回,我们则可以直接可以在成员上使用箭头函数并且直接调用参数,而不需要在使用bind方法。如TextInput的onChangeText,本身就带text返回。
onPhoneTextChange = (text) => { this.loginPhone = text;}<TextInput onChangeText={this.onPhoneTextChange} keyboardType={'phone-pad'} placeholder={'在此输入您的手机号'} underlineColorAndroid={'transparent'} placeholderTextColor={'#aaa'} defaultValue={this.loginPhone} autoFocus={true} clearButtonMode={'while-editing'} />
问题二:在设置一个组件 props 的时候直接设置对象或者数组
当我们需要给一个组件设置 style 的时候,有些时候我们会这样设置。
<View style={{flex:1}} />
或者
<View style={[styles.container,{backgroundColor: 'white'}]} />
解决方案
style 在 const styles = StyleSheet.create({}) 中统一赋值或者设置一个 const defaultstyle = {} ,将默认值保存成同一份引用。
render() { return ( <View style={styles.container}/> )}const styles = StyleSheet.create({ container: { flex:1, backgroundColor: 'white' },});
或者
render() { const defaultColor = [styles.container,{backgroundColor:'white'}]; return ( <View style={defaultColor}/> )}const styles = StyleSheet.create({ container: { flex:1, backgroundColor: '#F1F1F1' },});
总结
这些编码习惯都是直接设置props设置对象或数组带来性能损耗,而将这些数组或者对象保存成同一份引用,这样就能减少render。同时我们还可以使用 PureComponent 代替 Component ,减少 render 。
import React, { PureComponent} from 'react';class Login extends PureComponent {}
PureComponent 内部自带了实现了 shouldComponentUpdate,去判断这个组件是否是需要重新 render ,其实现的 shouldComponentUpdate 内部是一个浅比较。
import React, { Component} from 'react';class Login extends Component { shouldComponentUpdate(nextProps = {}, nextState = {}) { return 浅比较(nextProps,this.props)|| 浅比较(nextState,this.state); }}
继承 PureComponent 和上述代码带来的功能是一样的。
- React Native 编码习惯带来的性能问题
- react-native的性能
- React&React-Native的实践的问题
- React Native遇到的问题
- React Native的一些问题
- react-native遇到的问题
- 【React Native】导入github上react native遇到的问题。
- React Native性能优化
- React Native性能优化
- React Native性能优化
- Python编码带来的一些问题
- tomcat版本升级带来的编码问题
- Android React Native的使用细节问题
- react-native中碰到的问题
- 安装react-native遇到的问题
- 学习React Native想到的问题
- React Native 红屏问题的解决
- React native安装过程遇到的问题
- opencv_core244d.lib(opencv_core244d.dll) : fatal error LNK1112: 模块计算机类型“X86”与目标计算机类型“x64”冲突
- Android多渠道编译-依赖的渠道控制
- oracle登录报ORA-12541:无监听程序 ! 错误
- Android左右滑动控件实现开关的切换效果
- Python的迭代协议和迭代环境
- React Native 编码习惯带来的性能问题
- 生成一个可执行jar包、invalid header field
- 什么是DAO
- unity3D学习笔记之六 Material(材质)的几种RenderingMode(渲染模式)
- Android 自定义NumberPicker
- Linux下的crond和crontab
- matlab图像镜像
- Linux总线驱动设计(1)-总线驱动模型
- HTML CSS + DIV实现整体布局