zoukankan      html  css  js  c++  java
  • React.Component 和 React.PureComponent 、React.memo 的区别

    一 结论

    React.Component 是没有做任何渲染优化的,但凡调用this.setState 就会执行render的刷新操作。
    React.PureComponent 是继承自Component,并且对重写了shouldComponentUpdate周期函数,对 state 和 props 做了浅层比较,当state 和 props 均没有改变时候,不会render,仅可以用在ClassComponent中
    React.memo 功能同React.PureComponent,但React.memo 为高阶组件,既可以用在ClassComponent中 也可以用在 functionComponent中

    二 React.Component

    需要手动编写shouldCompoentUpdate进行 props和state的比较判断是否需要渲染render

    Class Sum extends React.Component {
          constructor(props){
                super(props);
                this.state = {
                      num:0
                }
          }
          shouldCompoentUpdate(nextProps,nextState){
                if(nextPorps.sum === this.props.sum && nextState.num === this.state.num){  
                      return false; // 当props 和state 值均没有改变时候,让render不渲染    
                }
                return ture; // 其他情况设置成允许渲染
          }
          render(){
                return (
                      <div>
                          <span>{this.state.num}</span>
                          <span>{this.props.sum}</span>
                      </div>
                )
          }
    }
    

    二 React.PureComponent 和 React.memo 的使用

    Class Sum extends React.PureComponent {
    // 会自动进行props 和 sate 的浅比较 
    }
    
    function Add (props){
          return (
                <div>sum = {props.y + props.x}</div>
          )
    }
    export default React.memo(Add)
    

    注意:当props 或者 state 为一个 Object类型时候,浅比较会失效 即 props ,state 发生改变,依旧会阻止render渲染。
    此时可以运用的方法有
    1 修改state时候,采用 object.assin({},)进行组件合并
    2 采用 解构赋值进行浅拷贝赋值,这样props或者state 就不再为原来的值了,可以触发render刷新操作
    3 当组件结构较复杂,存在较多 Object类型时候 建议改为使用React.Component

  • 相关阅读:
    反射:框架设计的灵魂
    Junit测试
    XML笔记
    map 的用法
    opencv总结1
    光源
    镜面反射
    openGL纹理对象
    GPU入门
    动态规划1
  • 原文地址:https://www.cnblogs.com/honkerzh/p/13855473.html
Copyright © 2011-2022 走看看