解决Component效率低下的两个问题

解决Component效率低下的两个问题

  1. 执行setState,即使是不改变状态数据,仍然会调用render()
  2. 当前组件调用render()时,其子组件也会调用render()

原因:Component中的shouldComponentUpdate()总是返回true

解决方法:

  1. 重写shouldComponentUpdate()方法,没词比较新旧state或props数据,如果有变化才返回true,如果没有就返回false
  2. 使用PureComponent
//方法一,重写shouldComponentUpdate()方法
shouldComponentUpdate(nextProps,nextState){
  //可以通过this.props和this.state与nextProps和nextState进行比较来决定返回true还是false
}
//方法二,使用PureComponent
//创建类组件的时候继承Component改为PureComponent
//但是PureComponent只是看浅层对比,看对象的地址是否变化,如果地址没变,PureComponent会认为state没有变化

posted @ 2021-11-22 14:44  BONiii  阅读(97)  评论(0)    收藏  举报