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即可。

  • 相关阅读:
    Knight Moves
    Knight Moves
    Catch him
    Catch him
    Linux查看硬件信息以及驱动设备的命令
    23种设计模式彩图
    Android开发指南-框架主题-安全和许可
    Android启动组件的三种主流及若干非主流方式
    ACE在Linux下编译安装
    void及void指针含义的深刻解析
  • 原文地址:https://www.cnblogs.com/zouyanzhi/p/12752372.html
Copyright © 2011-2022 走看看