首页 > 其他 > 详细

React.Component 和 React.PureComponent 、React.memo 的区别

时间:2020-10-22 00:05:24      阅读:54      评论:0      收藏:0      [点我收藏+]

一 结论

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

React.Component 和 React.PureComponent 、React.memo 的区别

原文:https://www.cnblogs.com/honkerzh/p/13855473.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!