zoukankan      html  css  js  c++  java
  • react性能优化

    一。为什么要进行性能优化?

    React是一个用于构建用户界面的JavaSctiput库,主要负责将数据转换为视图,保证数据和视图的统一。
    react通过重新render来保证数据和视图的统一,但当数据并没有变化时,视图需要重新渲染,就会造成不必要的性能浪费。

    例如:父组件调用子组件的时候,如果父组件渲染,但是子组件数据并没有改变,但是子组件会随之父组件进行重新render。

    二。性能优化的方法:

    1.shouldComponentUpdate:

    生命周期shouldComponentUpdate,当返回false的时候,组件就不会重新渲染。
    接收2个参数:nextProps(下一次更新的props) 和 nextState(下一次更新的state值)
    只需要当 nextProps.name === this.props.name 时,return false,Children 就不会重新渲染

    2.PureComponet:

    子组件直接继承 PureComponent, 我们就不需要写 shouldComponentUpdate。 react 会自动帮我们做对比 优化

    如果穿入的值比较简单,就可以使用react 提供的语法糖 PureComponet
    
    class Children extends PureComponent {
         render () {
            console.log(' Children render ')
            return (<div>Children Component name { this.props.name }</div>)
          }
     }

    缺陷:

    PureComponent 是有局限性的,只有传入值属性的对比,如果传入的值内部发生变化,PureComponent 是会出现,数据更新,视图不更新的情况的  

    3.memo

    在我们使用class 去创建组件时,可以使用PureComponent,但当使用 函数组件时,就没办法继承 PureComponent,这个时候需要使用memo,利用memo包裹一个函数组件,返回一个新组件,
    就可以实现PureComponent的功能。 function ChildrenFunc (props) { return ( (<div>Children Component name { props.human.name} age { props.human.age}</div>) )
    } const Children = memo(ChildrenFunc) 

      

    参考:https://blog.csdn.net/landl_ww/article/details/95600969

     

  • 相关阅读:
    递归算法
    linux下如何使用split
    什么是OPTEE-OS
    ubuntu 18.04 64bit如何编译安装内核
    ubuntu 18.04 64bit没有声音如何解决
    如何解决ubuntu报的错误:You must put some 'source' URIs in your sources.list
    linux下如何安装解压工具rar
    如何将一个已有的仓库推送到一个空的新仓库中
    ubuntu 18.04 64bit下如何安装python开发工具jupyter
    ubuntu 18.04 64bit下如何安装python开发工具jupyterhub
  • 原文地址:https://www.cnblogs.com/liumcb/p/14049804.html
Copyright © 2011-2022 走看看