zoukankan      html  css  js  c++  java
  • Component VS PureComponent

     Component VS PureComponent

    import React from 'react';
    import PropTypes from 'prop-types';

    export default class Button extends React.Component {
        static propTypes = {
            text: PropTypes.string.isRequired
        }
        static defaultProps = {
            text: 'Click me'
        }
        constructor(props) {
            super(props);
            this.state = { count: props.count };
            this.handleClick = this.handleClick.bind(this);
        }
        handleClick() {
            //do something
        }
        shouldComponentUpdate(nextProps, nextState) {
            if (this.props.text !== nextProps.text) {
                return true;
            }
            if (this.state.count !== nextState.count) {
                return true;
            }
            return false;
        }
        render() {
            const { text } = this.props;
            return <button type="button" onClick={this.handleClick}>
                {text}
            </button>
        }
    }

    当组件的props或者state发生变化的时候,React会对组件当前的Props和State分别与nextProps和nextState进行比较,如果有变化,当前组件及其子组件就会重新渲染。

    为了避免不必要的重新渲染,我们通过实现shouldComponentUpdate来优化性能(详见黄色高亮部分)(只在需要的时候进行更新)。

    针对以上需求,React提供了PureComponent来自动帮我们实现以上需求,这样可以简化代码,提高性能。但是PureComponent中自动实现的shouldComponentUpdate只是对props和state进行了浅比较,所以当props和state是嵌套对象/数组等复杂类型时,达不到预期的效果。example:

    this.state = { arr: ["Hello"] };
    
    handleClick(){
        const tempArr = this.state.arr;
        tempArr.push("World");
        this.setState({ arr: tempArr })
    }

    arr中新增了元素,但是由于state只进行了浅比较,this.state.arr与nextState.arr指向的仍是同一个数组,组件不会进行重新渲染。

    解决办法:生成一个新的数组赋值给state.arr即可。

  • 相关阅读:
    古谚、评论与论断、名篇与名言
    重读《西游记》
    重读《西游记》
    命名之法 —— 时间、季节、地点
    命名之法 —— 时间、季节、地点
    文言的理解 —— 古时的称谓、别称、别名
    文言的理解 —— 古时的称谓、别称、别名
    Oracle GoldenGate for Oracle 11g to PostgreSQL 9.2.4 Configuration
    瀑布 敏捷 文档
    POJ 1325 ZOJ 1364 最小覆盖点集
  • 原文地址:https://www.cnblogs.com/zouyanzhi/p/12752372.html
Copyright © 2011-2022 走看看