ReactNative性能优化


目录


-)console.log

//React Native中有一个全局变量__DEV__用于指示当前运行环境是否是开发环境。
//我们可以据此在正式环境中替换掉系统原先的console实现
if (!__DEV__) {
  global.console = {
    info: () => {},
    log: () => {},
    warn: () => {},
    debug: () => {},
    error: () => {},
  };
}

-)PureComponent

shouldComponentUpdate return true或false决定了组件是否会进行render

//PureComponent相当于在原来的shouldComponentUpdate时
//比较新传入的属性或状态的值是否发生了改变
//return true说明改变了就回去render
shouldComponentUpdate(newProps,newState){
  return swallowCompare(newProps,this.props) || swallowCompare(newState,this.state);
}
<Son msg={'信息'}/>  //传递常量

父组件重新render会触发子PureComponent组件的
componentWillReceiveProps->
shouldComponentUpdate-> @end

<Son msg={this.state.msg}/> 传递state

父组件重新render会触发子PureComponent组件的
componentWillReceiveProps->
shouldComponentUpdate->
componentWillUpdate->
render->
componentDidUpdate ->@end
——

-)注意方法的创建

方法的定义应该使用 onPress=()=>{}.
render中直接调用this.onPress即可,否则render时会创建新的引用,从而造成子组件认为属性发生了变化而重新render

//正确
<Son onPress={this._onPress}> 
//Father render的时候,箭头函数重新创建了引用,
//Son会认为是新的props,从而就算是PureComponent也会重新render
<Son onPress={()=>{console.log('1')}}> 

-)setNativeProps

对于有些比较大的JSX页面,有时仅仅为了动态修改其中一小块的样式,如果采用setState()来动态改变样式值,render会造成整个view树的diff。可以采用如下代码。

注意:此方法不推荐使用,可读性较差。应该合理的拆分和细化组件,来控制组件是否应被合理的render

this.refs.view.setNativeProps({
  style:{
    width:100,
    height:1,
    position:'absolute',
    left: this.leftBegin * SCREEN_WIDTH,
  }
})

-)InteractionManager

componentDidMount() {
  //在用户有任何触摸操作 或 应用有任何动画的时候 都不执行此回调
  //也就是可以适当延迟执行this.fetchData()
  //推迟render的过程可以避免卡顿
  //也可早点fetchData ,在fetchData获取数据去setState时执行runAfterInteractions
  InteractionManager.runAfterInteractions({
    this.fetchData();
  })
}

参考资料

官网
https://www.jianshu.com/p/57f2e987c879


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、声明方法函数时,要尽量使用 方法名= ()=> {},这样会减少方法引用的次数。然后在调用的时候,直接使...
    亦晴工作室阅读 717评论 1 2
  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 2,860评论 1 18
  • 3. JSX JSX是对JavaScript语言的一个扩展语法, 用于生产React“元素”,建议在描述UI的时候...
    pixels阅读 2,891评论 0 24
  • Python数据处理模块结构总览 Python版本:2.7.13 Http Server:Tornado Http...
    EddyLiu2017阅读 581评论 0 0
  • 我不知道该怎么和生活中无法失去的人说再见 所以我没有说再见就离开了 ​​​​
    怪猫Cc阅读 162评论 0 0