简体   繁体   English

在React渲染方法上分解道具时的性能问题

[英]Performance issue when destructuring props on React render method

I was wondering if destructuring props on the render method will see the performance hurt, since every time you are creating them a new constant is created, and at the time of shallow comparing (in case you are using PureComponent), the shallow comparison will return false, thus re-rendering any children. 我想知道在render方法上销毁道具是否会损害性能,因为每次创建它们时都会创建一个新常量,并且在进行浅表比较时(如果使用的是PureComponent),将返回浅表比较错误,因此重新渲染任何孩子。

Se example below: 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>
    )
  }
}

If you were to destructure an object from this.props , the value in the new variable would be a pointer to that object, a string. 如果要从this.props解构对象,则新变量中的值将是指向该对象的指针,即字符串。 This is the same primitive string that would be sent if you passed this.props.complexObject directly as a prop. 如果您直接将this.props.complexObject作为prop传递,则该字符串与发送的原始字符串相同。 Therefore so long as the object reference is the same then PureComponent's shallow compare will return true. 因此,只要对象引用相同,则PureComponent的浅表比较将返回true。

This can lead to problems if you mutate your complex object because the pointer would remain the same, and the PureComponent would not update. 如果您对复杂对象进行突变,则可能导致问题,因为指针将保持不变,并且PureComponent不会更新。 This is why when any value changes in your complex object, you want to make a complete clone and pass that. 这就是为什么当复杂对象中的任何值更改时,您都希望进行完整的克隆并传递该克隆。 This would be a new pointer and would get caught by the shallow compare and make the PureComponent update. 这将是一个新指针,并且将被浅表比较捕获并进行PureComponent更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM