PureComponent 是 Component 的子类:内置了 shouldComponentUpdate,对 props 和 state 做一层浅比较,全部相等就跳过本次渲染。写法上只需把 extends Component 换成 extends PureComponent,声明式地拿到优化,适合没有复杂 props 的展示型类组件。
与 React.memo 同源同限制:浅比较只比第一层,对象内部深层变化检测不到,所以必须坚持不可变更新;新旧 state 返回同一对象引用时更新会无声丢失。函数组件请用 memo 替代,类组件仍在维护的老项目里 PureComponent 少量使用即可。
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> ); } }