如何在React.js中使用PureComponent

  介绍

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

<强>一、介绍PureComponent

15.3反应在2016.06.29发布了,这个版本最值得关注的是支持了反应。PureComponent,它取代了之前的pure-render-mixin。在本文中,我们将讨论PureComponent的重要性和使用场景。

反应。PureComponent最重要的一个用处就是优化反应应用,这很容易快速地实现。使用反应。PureComponent对性能的提升是非常可观的,因为它减少了应用中的渲染次数。

如何在反应。js中使用PureComponent

PureComponent改变了生命周期方法<代码> shouldComponentupdate> 状态或者<代码>道具> 渲染方法,因此,你不用手动写额外的检查,就可以在很多组件中改变<代码> ,例如:

if  (this.state.someVal  !==, computedVal), {   ,this.setState ({, someVal: computedVal })   }

根据反应源码,如果组件是纯组件(纯组件),那么一下比较是很容易理解的:

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

其中,<代码> shadowEqual> 道具和<代码> ,这就意味着嵌套对象和数组是不会被比较的。

深比较操作是非常昂贵的,同时,如果这个组件还是纯组件(PureComponent),那么深比较将会更浪费。另外,你也可以使用<代码> shouldComponentUpdate> 道具或<代码>国家:

shouldComponentUpdate (nextProps, nextState), {   ,return  nextProps.user.id ===, props.user.id;   }

除此之外,你可以使用不变的属性。这种情况下,属性的比较是非常容易的,因为已存在的对象不会发生改变,取而代之的是重新创建新的对象,其中,不可变的。js就是非常好的不可变的库。

<强>二、使用PureComponent

PureComponent节约了我们的时间,避免了多余的代码。那么,掌握如何正确使用它是非常重要的,否则如果使用不当,它就无法发挥作用。因为PureComponent仅仅是浅比较(阴影的比较),所以改变组件内部的<代码>道具> ,它将不会发挥作用,例如,让我们想想这样一种情况,父组件有一个渲染方法和一个点击处理方法:

handleClick (), {   {物品},let =this.state      ,items.push (& # 39; new-item& # 39;)   ,this.setState ({}, items )   }      呈现(),{   ,return  (   & lt;才能div>   ,,& lt; button  onClick={this.handleClick},/比;   ,,& lt; ItemList 项目={this.state.items},/比;   & lt;才能/div>   ,)   }

如果ItemList是纯组件(PureComponent),那么这时它是不会被渲染的,因为尽管<代码> this.state。项目> handleClick (), {   ,this.setState (prevState =祝辞,({   ,,字:prevState.items.concat ((& # 39; new-item& # 39;])   ,}));   }

如果一个纯组件(PureComponent)的国家或道具引用了一个新对象,那么这个组件就会被重新渲染(重新呈现)。这暗示着,如果不想损失PureComponent的优点,那么我们应该避免以下的结构:

& lt; Entity 值={this.props.values  | |,[]}/祝辞

如上面代码,新数组,即便是空数组,总是会迫使组件重新渲染。为了避免这个问题,你可以使用<代码> defaultProps> & lt; CustomInput  onChange={e =祝辞,this.props.update (e.target.value)},/在

在纯组件(PureComponent)被创建时,因为函数的新对象被创建了,所以它会获得新数据,并且重新渲染。解决这个问题最简单的方法就是:在组件的构造函数方法中使用绑定。

构造函数(道具),{   超级才能(道具)   时间=this.update 才能;this.update.bind(这)   }   更新(e), {   this.props.update才能(e.target.value)   }   呈现(),{   return 才能;& lt; MyInput  onChange={this.update},/比;   }

如何在React.js中使用PureComponent