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

  • 相关阅读:
    ASP.NET编程的十大技巧
    C#学习心得(转)
    POJ 1177 Picture (线段树)
    POJ 3067 Japan (树状数组)
    POJ 2828 Buy Tickets (线段树)
    POJ 1195 Mobile phones (二维树状数组)
    HDU 4235 Flowers (线段树)
    POJ 2886 Who Gets the Most Candies? (线段树)
    POJ 2418 Cows (树状数组)
    HDU 4339 Query (线段树)
  • 原文地址:https://www.cnblogs.com/zouyanzhi/p/12752372.html
Copyright © 2011-2022 走看看