PureComponent如何在反应中使用

  介绍

PureComponent如何在反应中使用?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

<强>反应避免重复渲染

反应在渲染出的UI内部建立和维护了一个内层的实现方式,它包括了从组件返回的反应元素。这种实现方式使得反应避免了一些不必要的创建和关联DOM节点,因为这样做可能比直接操作JavaScript对象更慢一些,它被称之为“虚拟DOM”。

当一个组件的道具或者状态改变时,反应通过比较新返回的元素和之前渲染的元素来决定是否有必要更新实际的DOM。当他们不相等时,反应会更新DOM。

在一些情况下,你的组件可以通过重写这个生命周期函数shouldComponentUpdate来提升速度,它是在重新渲染过程开始前触发的。这个函数默认返回真,可使反应执行更新:

shouldComponentUpdate (nextProps, nextState), {   ,return 真实;   }

<>强举例

如果想让组件只在<代码> props.color> 状态。数> shouldComponentUpdate :

class  CounterButton  extends  React.Component  {   ,构造函数(道具){   超级才能(道具);   this.state 才能=,{数:1};   ,}      ,shouldComponentUpdate (nextProps, nextState), {   if 才能;(this.props.color  !==, nextProps.color), {   ,,return 真实;   ,,}   if 才能;(this.state.count  !==, nextState.count), {   ,,return 真实;   ,,}   return 才能;假;   ,}      ,使(){   return 才能;   ,,& lt;按钮   ,,,颜色={this.props.color}   ,,,onClick={(),=祝辞,this.setState (state =祝辞,({数:,state.count  +, 1}))}祝辞   ,,,数:,{this.state.count}   ,,& lt;/button>   ,,);   ,}   }

在以上代码中,<代码> shouldComponentUpdate> props.color 和<代码>状态。数> 反应。PureComponent> class  CounterButton  extends  React.PureComponent  {   ,构造函数(道具){   超级才能(道具);   this.state 才能=,{数:1};   ,}      ,使(){   return 才能;   ,,& lt;按钮   ,,,颜色={this.props.color}   ,,,onClick={(),=祝辞,this.setState (state =祝辞,({数:,state.count  +, 1}))}祝辞   ,,,数:,{this.state.count}   ,,& lt;/button>   ,,);   ,}   }

<>强PureComponent

<强>原理

当组件更新时,如果组件的道具和状态都没发生改变,呈现方法就不会触发,省去虚拟DOM的生成和比对过程,达到提升性能的目的。具体就是反应自动帮我们做了一层浅比较:

if  (this._compositeType ===, CompositeTypes.PureClass), {   shouldUpdate 才能=,! shallowEqual (prevProps, nextProps), | |, ! shallowEqual (nextState inst.state也);   }

而shallowEqual又做了什么呢?会比较对象。键(状态|道具)的长度是否一致,每一个关键是否两者都有,并且是否是一个引用,也就是只比较了第一层的值,确实很浅,所以深层的嵌套数据是对比不出来的。

<强>问题

大部分情况下,你可以使用反应。PureComponent而不必写你自己的shouldComponentUpdate,它只做一个浅比较。但是由于浅比较会忽略属性或状态突变的情况,此时你不能使用它。

class  ListOfWords  extends  React.PureComponent  {   ,使(){   return 才能;& lt; div> {this.props.words.join (& # 39; & # 39;)} & lt;/div>;   ,}   }      class  WordAdder  extends  React.Component  {   ,构造函数(道具){   超级才能(道具);   this.state 才能=,{   ,,,话说:[& # 39;marklar& # 39;】   ,,};   时间=this.handleClick 才能;this.handleClick.bind(这个);   ,}      ,handleClick (), {//才能,却;能够section  is  bad  style 以及causes  a  bug   const 才能;words =, this.state.words;   words.push才能(& # 39;marklar& # 39;);   this.setState才能({词:,话说});   ,}      ,使(){   return 才能;   ,,& lt; div>   ,,,& lt; button  onClick={this.handleClick},/比;   ,,,& lt; ListOfWords 词={this.state.words},/比;   ,,& lt;/div>   ,,);   ,}   }

PureComponent如何在反应中使用