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

posted @ 2020-04-22 15:27  芝芝07  阅读(101)  评论(0编辑  收藏  举报