跳转到主要内容

PureComponent

类组件的性能优化:对 props/state 做浅比较,跳过不必要的渲染。

ClassLegacy Style

类型签名

TypeScript
class PureComponent<P = {}, S = {}, SS = any> extends Component<P, S, SS> {}

说明

  • PureComponent 会对 props 和 state 做浅比较,决定是否跳过渲染。
  • 浅比较要求你遵循不可变更新;可变对象的 mutation 会导致更新被“错过”。

版本与稳定性

  • 稳定性:稳定(类组件 API)。
  • 推荐替代:函数组件通常使用 memo 做相似优化。

关键用法

TypeScript
import React from 'react';

type Props = { value: number };

export class CounterView extends React.PureComponent<Props> {
  render() {
    return <p>{this.props.value}</p>;
  }
}

常见坑

TypeScript
// ❌ 浅比较 + 可变对象 会导致视图不更新
// 例如:props.user 是同一个对象引用,但内部字段被你直接改了

PureComponent 的浅比较要求你遵循不可变更新。如果你需要在函数组件里做类似优化,优先使用 memo,并搭配不可变数据结构。

PureComponent - React API 参考 - React 文档