前端进阶之路(三)React组件重新渲染之shouldComponentUpdate和React.PureComponent

state作为react的一个重要的部分,固然自动渲染给我们省了很多的麻烦,然而并不是我们想让他不渲染就很容易做到的
一些时候,state的重新渲染机制导致了不必要的渲染,所以研究一下用来一些特定的情况下也是很有必要的

一. shouldComponentUpdate

(shouldComponentUpdate可能会导致bug,并不建议使用)
关于shouldComponentUpdate,React.js官网是这么解释的:

Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

React默认在每一次state或者props改变之后进行渲染,会在每一次新的props或者state接受之前被调用,但是页面第一次渲染或者forceUpdate()的时候不会被调用.
如果对shouldComponentUpdate进行设置,多半格式是这样的,返回true或者false:

 shouldComponentUpdate(nextProps, nextState) {
   if (this.props.count !== nextProps.count) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

什么是不必要的组件渲染,并不是state或者props的值不改变,组件就不会重新渲染
e.g

this.setState({
       Number:this.state.Count
})

虽然Count的值并没有改变,但是React会对组件重新渲染,就会造成组件不必要的重新渲染;另外没有状态交换的父组件的重新渲染也会导致自组件没有必要的重新渲染。但是即使返回false,组件依然有可能会重新渲染.


另外,shouldComponentUpdate不可以直接比较Object,会直接true阻止渲染,因为不同的引用指向的其实是对内存中的同一个对象

nextProps.countObject.count == this.props.countObject.count

如何解决这一问题:

  1. ES6:Object.assign({}) 浅拷贝(克隆)、对象属性的合并

var Obj = Object.assign({},obj1,obj2); //{}叫目标对象,obj1和obj2是源对象。开源对象的数量为一个或者多个。Object.assign 拷贝的是属性值(相当于当前数据的快照),会跳过那些值为 null 或 undefined 的源对象。

对象属性合并:将obj1和obj2里面的属性添加到{}中去,若obj1和obj2属性名有冲突,后面的属性将会覆盖前面的属性

  1. JSON.parse(JSON.stringify(data)) 深拷贝(相当于原有数据的拷贝)
  2. immutable.js
  3. React.PureComponent:对道具和状态进行浅层次的比较,并减少必要的机会

二. React.PureComponent

PureComponent对道具和状态进行浅层次的比较,并不能定制shouldComponentUpdate(),并减少必要的渲染。
如果props和state的数据结构复杂,则无法正确渲染,只有在几种情况注意:

  1. 有相同的props和state,pureComponent的渲染结果相同
  2. 使用forceUpdate()深层的数据改变,pureComponent值进行浅层数据比较,可能因为深层数据改变但是渲染没有更新而产生错误的渲染判断
  3. 使用不可变的对象来加速nested数据的快速比较
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值