PureComponent和Component的区别

PureComponent通过浅比较优化渲染,适用于状态简单的情况。在组件状态复杂时避免使用,且其父组件及子组件需同样为PureComponent以保持预期渲染效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PureComponentcomponent相比,PureComponent通过propstate的浅比较来实现shouldComponentUpdate,在某些情况下,用PureComponent可以提高页面的渲染性能。

// shallowEqual 会比较 Object.keys(state | props) 的长度是否一致,每一个 key 是否两者都有,
// 并且是否是一个引用,也就是只比较了第一层的值,确实很浅,所以深层的嵌套数据是对比不出来的
if (this._compositeType === CompositeTypes.PureClass) {
    shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState);
}

当组件状态十分复杂的时候,建议不要去使用PureComponent。同时PureComponent的父组件,其子组件也必须是PureComponent,否正很有可能达不到预期的渲染效果。建议PureComponent主要用在逻辑简单的展示性子组件中。

import React, { PureComponent } from 'react';

class PureComponentTest extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            isClick: false,
            wordList: []
        }
    }

    handleClick = () => {
        this.setState(preState => ({
            isClick: !preState.isClick
        }))
    }

    handleAddWordClick = () => {
        // concat、ES6的扩展运算符(spread) 的操作不会对元数据产生影响
        this.setState(preState => ({
            // wordList: preState.wordList.concat(" this ")
            wordList: [...preState.wordList," this "]
        }))

        // 解析赋值两个变量具有相同的引用,指向同一个对象,wordList的push操作同时改变了this.state.wordList的值,
        // PureComponent 会对 props 和 state 进行浅层比较,因此两者不会发生改变,从而不会重新渲染
        
        // const { wordList } = this.state;
        // wordList.push(" this ")
        // this.setState({
        //     wordList
        // })
    }

    render() {
        const { isClick, wordList } = this.state;
        return (
            <div>
                <button onClick={this.handleClick}>点击</button>
                <div>{isClick.toString()}</div>

                <button onClick={this.handleAddWordClick}>点击增加单词</button>
                <div>{wordList.join(",")}</div>
            </div>
        )
    }
}

export default PureComponentTest;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值