手机版

使用反应优化子组件渲染

时间:2021-08-24 来源:互联网 编辑:宝哥软件园 浏览:

在react中,父组件的重新呈现将触发子组件的重新呈现,但在某些情况下,我们会觉得这是多余的,例如:

父组件没有将道具传递给子组件。新传递的道具渲染结果不变。Class a extends report.component { render(){ console . log(' render ')返回div这是一个component/div } } Class main extends react.component { render(){ return(div//单击按钮将调用renderbutton onclick={()=this。setstate({ a :1 })} main/button a//div)} }为了解决这个问题,需要将其分为ES6类组件和功能组件:

类组件

使用shouldComponentUpdate判断道具和状态以决定是否渲染

a类扩展反应。party {shouldcomponenttupdate(下一个道具,下一个状态){//两个道具对比返回下一个道具。a===这个。道具。a?true : true } render(){ console . log(' render ')返回div这是一个component/div}}类main extends react.component {//.render () {return (div)按钮onclick={()=this。setstate({ a : 1 })} main/button a a a={ this。state.a}//div)}}通过返回false跳过此更新

使用反应。PureComponent,不同于React。组件,因为它内置了shouldComponentUpdate来对道具和状态进行简单的比较,并跳过更新

//purecomponent Class a extends reach . purecomponent { render(){ console . log(' render ')return div这是一个组件/div } } Class main extends react.component { state={ a : 1 } render(){ return(div)button onclick={()=this。setstate({ a : 1 })} main/button a a={ this。state.a}//div)}}函数组件

用高阶组件React.memo包装功能组件,类似于类组件的PureComponent,也是一种道具的浅层次比较,决定是否更新

const A=props={ console . log(' render main ')返回div这是一个组件/div}//React.memo包A const B=react . memo(A)const main=props={ const[A,Seta]=usestate(1)console . log(' render main ')返回(div//让父组件重新呈现按钮onclick={()=Seta(A(1)} main/button//一直传入相同的道具不会使子组件重新呈现B={ 1 }//div)}

其他的

上面提到的浅比较是根据内存地址来判断是否相同:

//extends resact。组件类a扩展响应。组件{ render(){ console . log(' render a ')console . log(这。道具)返回div这是组件A/div } } Main类扩展了React。组件{ test=[1,2,3]render(){ console . log(' render main ')返回(div button onclick={()={//父组件render this . setstate({ })this . test . push(4)} } main/button a test={ this . test }//div)}

使用React.component:

使用反应。purecomponents :

使用反应组件,点击它,然后子组件将被重新渲染。更改为“反应”后。PureComponent,单击按钮子组件将不会呈现。因此PureComponent根据前后内存地址来判断是否相等,所以在将函数作为道具传递给子组件时,使用内联箭头函数的形式会导致重新渲染;子组件;因此,箭头函数可以用作成员变量,然后函数引用可以作为道具传递。

以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。

版权声明:使用反应优化子组件渲染是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。