我想知道在 render 方法上解构 props 是否会影响性能,因为每次创建它们时都会创建一个新常量,并且在浅层比较时(如果您使用的是 PureComponent),浅层比较将返回 false,从而重新渲染任何子项。
Se 示例如下:
export default class Input extends React.PureComponent {
render () {
// creating new constants, that in case they are no primitives
// will return false when shallow comparing them and trigger
// child component re-render
const { type, value, required } = this.props
return (
<div className={cx('Input')}>
<APureComponent type={type} value={value} required={required} />
</div>
)
}
}
最佳答案
如果您要从 this.props
中解构一个对象,新变量中的值将是指向该对象的指针,一个字符串。如果您直接将 this.props.complexObject
作为 Prop 传递,这与将发送的原始字符串相同。因此,只要对象引用相同,PureComponent 的浅层比较就会返回 true。
如果您改变复杂对象,这可能会导致问题,因为指针将保持不变,并且 PureComponent 不会更新。这就是为什么当您的复杂对象中的任何值发生变化时,您想要制作一个完整的克隆并传递它。这将是一个新指针,会被浅层比较捕获并进行 PureComponent 更新。
关于javascript - 在 React 渲染方法上解构 Prop 时的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50274614/