Skip to content

Pure 组件

一句话解释

pure 组件是 类组件那个 implements shouldComponentUpdate 使用 shallow prop and 状态 comparison 到 skip 不必要 re-渲染.

用大白话说

React.PureComponent 是类 组件 variant 那个 automatically implements shouldComponentUpdate with a shallow comparison of props and state. If the shallow comparison says nothing changed, the component skips re-rendering.

This is the class component equivalent of React.memo for function components. It prevents re-renders when the parent re-renders but the props/state are shallowly equal.

Caveat: shallow comparison only checks one level deep. If you pass a new object or array with the same contents, the shallow comparison sees a different reference and re-renders anyway. For nested objects, you need deep comparison (which is expensive) or immutable data structures.

示例

jsx
class MyComponent extends React.PureComponent {
  render() {
    return <div>{this.props.value}</div>;
  }
}

// Only re-renders when this.props.value changes (shallowly).

PureComponent 做 shallow comparison 的 Props. 如果值 是相同 primitive, 组件 skips re-渲染.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表