PureComponent的作用及一些使用陷阱

import React from "react";
class component7 extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            words: ["mark"]
        };
    }
    handleClick() {
        console.log("handleClick");
        let words = this.state.words;
        words.push("marklar");
        this.setState({ words: words });
    }
    handleClick2() {
        console.log("handleClick2");
        let words = this.state.words.map(val => val);
        words.push("marklar");
        this.setState({ words: words });
    }
    render() {
        return (
            <div>
                <button
                    onClick={() => {
                        this.handleClick();
                    }}
                >
                    往this.state.words中push内容
                </button>
                <button
                    onClick={() => {
                        this.handleClick2();
                    }}
                >
                    改变this.state.words指向的数组
                </button>
                <div>{this.state.words.join(",")}</div>
            </div>
        );
    }
}

export default component7;

PureComponent只会对this.state.words进行一次浅比较,虽然数组里面新增了元素,但是this.state.words与nextState.words指向的仍是同一个数组,因此this.state.words !== nextState.words 返回的便是flase, 所以不会出发render函数重新渲染

results for ""

    No results matching ""