React 词条目录
前端Wiki/词条/PureComponent

PureComponent

定义自带浅比较优化的类组件基类,props 与 state 无变化时跳过重渲染

PureComponent 是 Component 的子类:内置了 shouldComponentUpdate,对 props 和 state 做一层浅比较,全部相等就跳过本次渲染。写法上只需把 extends Component 换成 extends PureComponent,声明式地拿到优化,适合没有复杂 props 的展示型类组件。

与 React.memo 同源同限制:浅比较只比第一层,对象内部深层变化检测不到,所以必须坚持不可变更新;新旧 state 返回同一对象引用时更新会无声丢失。函数组件请用 memo 替代,类组件仍在维护的老项目里 PureComponent 少量使用即可。

JavaScript
import React, { PureComponent } from 'react';

class Greeting extends PureComponent {
  render() {
    console.log('渲染', this.props.name);   // 浅比较后不再渲染
    return <h3>你好,{this.props.name}</h3>;
  }
}

class App extends React.Component {
  state = { count: 0 };
  render() {
    return (
      <div>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          计数 {this.state.count}
        </button>
        <Greeting name="固定名称" />
      </div>
    );
  }
}
⚠ 常见误区
🔗 相关词条重渲染与 memo函数组件与元素渲染
← 返回来源章节函数组件与元素渲染