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



作者:玄策
链接:https://www.jianshu.com/p/d479e7c52b95

猜你喜欢

转载自blog.csdn.net/Free_Wind22/article/details/81869012