美文网首页
Component和 PureComponent对比

Component和 PureComponent对比

作者: any_5637 | 来源:发表于2019-10-31 20:23 被阅读0次

    React.Component和 React.PureComponent

    在开发的时候,偶然看到别人的代码使用了 React.PureComponent进行继承,我也跟着复制粘贴,但是并不知道他到底有什么作用,于是下来去了解了一下他两的区别,总结一下。
    PureComponent使用浅比较的方式对比props和state,实现了shouldComponentUpdate()函数,在某些情况下,使用PureComponent可以减少render函数的执行,提升性能。

    • 组件继承component:
    export default class Page extends React.Component{
      constructor(props) {
        super(props);
        this.state = {
          isShow:false,
        };
        console.log('1');
      }
      componentDidUpdate() {
        console.log("componentDidUpdate")
      }
    
      @Bind()
      onClick() {
        this.setState({
          isShow: true,
        });
      };
      render() {
        console.log('2');
        return (
          <div>
            <button onClick={this.onClick}>点击</button>
            <div>
             {this.state.isShow.toString()}
            </div>
          </div>
        );
      }
    }
    

    在首次渲染页面的时候,依次打印:'1', '2',当第一次点击按钮之后,打印'2', 'componentDidUpdate',在每次点击按钮之后,都会打印'2', 'componentDidUpdate',说明每点击一次,虽然state中的值没有改变,都会调用render()和componentDidUpdate()方法,触发页面的重新渲染,通常情况下需要我们重新手动调用shouldComponentUpdate()来判断state的值是否有改变,来决定页面是否重新渲染。
    因此,继承自Component中的组件shouldComponentUpdate()默认情况下总是返回true,总是会触发页面的重新渲染。

    • 组件继承pureComponent:
    export default class Page extends React.PureComponent{
      constructor(props) {
        super(props);
        this.state = {
          isShow:false,
        };
        console.log('1');
      }
      componentDidUpdate() {
        console.log("componentDidUpdate")
      }
    
      @Bind()
      onClick() {
        this.setState({
          isShow: true,
        });
      };
      render() {
        console.log('2');
        return (
          <div>
            <button onClick={this.onClick}>点击</button>
            <div>
             {this.state.isShow.toString()}
            </div>
          </div>
        );
      }
    }
    

    在首次渲染页面的时候,依次打印:'1', '2',当第一次点击按钮之后,打印'2', 'componentDidUpdate',在每次点击按钮之后,没有输出。在purComponent源码中:

      // 这个变量用来控制组件是否需要更新
      var shouldUpdate = true;
      // inst 是组件实例
      if (inst.shouldComponentUpdate) {
        shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
      } else {
        if (this._compositeType === CompositeType.PureClass) {
          shouldUpdate = !shallowEqual(prevProps, nextProps) ||
            !shallowEqual(inst.state, nextState);
        }
      }
    

    判断新旧属性和状态是否相等,是否需要重新渲染子组件,减少render()方法的触发,节省了在虚拟DOM生成与对比的过程,性能得到提升。
    PureComponent默认实现的shouldComponentUpdate()方法使用的是浅比较:即值的比较或引用的比较, 不会进行深层次的对比,所以当props或state的值是引用类型时,即使对象的值改变了,但是对象的引用没变。

    export default class Page extends React.PureComponent{
      constructor(props) {
        super(props);
        this.state = {
          isShow: [1,2],
        };
        console.log('1');
      }
      componentDidUpdate() {
        console.log("componentDidUpdate")
      }
    
      @Bind()
      onClick() {
        const { isShow } = this.state;
        isShow.push(1);
        this.setState({
          isShow,
        });
        console.log(this.state.isShow);
      };
      render() {
        console.log(this.state.isShow);
        return (
          <div>
            <button onClick={this.onClick}>点击</button>
            {
               arr.map(item => <span key={item}>{item}</span>)
            }
          </div>
        );
      }
    }
    

    在上面这段代码中,初次渲染打印'1',[1,2],点击按钮之后,打印出[1,2],render()函数没有执行,页面上展示的只有1 2。

    总结

    1. PureComponent已经用浅层对比props、state的方式替我们实现了shouldComponentUpdate(), 不仅能影响自身,还会影响其子组件;
    2. PureComponent 某些情况下(props或state的值不经常变动, 因为浅比较也会耗时)可以提升性能;

    遗留问题

    PureComponent只是进行浅比较,无法判断复杂数据类型(引用类型)的变化,还需要下来进行深入的研究。

    相关文章

      网友评论

          本文标题:Component和 PureComponent对比

          本文链接:https://www.haomeiwen.com/subject/lbizvctx.html