PureComponent 不直接声明shouldComponentUpdate。您无法使用this.shouldComponentUpdate 访问它。在 React 源代码中有一个 shouldUpdate 变量:
(以下源代码已简化)
// default is true
var shouldUpdate = true;
if (inst.shouldComponentUpdate) {
shouldUpdate = inst.shouldComponentUpdate(
nextProps,
nextState,
nextContext,
);
} else {
// if it's a PureComponent
if (this._compositeType === ReactCompositeComponentTypes.PureClass) {
shouldUpdate =
!shallowEqual(prevProps, nextProps) ||
!shallowEqual(inst.state, nextState);
}
}
// ...
if (shouldUpdate) {
// re-render ..
}
因为它只是浅相等,所以下面的代码返回 false,你会得到一个重新渲染:
const propA = { foo: 'bar' }
const nextPropA = { foo: 'bar' }
shallowEqual(propA, nextPropA) // false
因此请谨慎使用对象和数组。要证明 PureComponent 有效,请参见此示例 (v15.6):https://codepen.io/CodinCat/pen/eRdzXM?editors=1010
点击按钮不会触发Foo的渲染:
这是 PureComponent 可能不适合您的另一个示例:https://codepen.io/CodinCat/pen/QgKKLg?editors=1010
唯一的区别是<Foo someProp={{ foo: 'bar' }} />
因为{ foo: 'bar' } !== { foo: 'bar' },React 每次都会重新渲染。所以直接在 props 中写 inline 对象和数组并不是一个好习惯。一个常见的错误是编写内联样式:
<Foo style={{ color: 'pink' }} />
在这种情况下,Foo 将始终重新渲染,即使它是 PureComponent。如果您遇到此问题,您可以简单地提取对象并将其存储在某处,例如:
const someProp = { foo: 'bar' }
<Foo someProp={someProp} />
从someProp === someProp 开始,PureComponent 就可以工作了。