簡體   English   中英

在React組件中多次破壞道具?

[英]Destructing Props Multiple Times in React Component?

當我發現自己在react component多次使用相同的props時(例如,在該組件的不同方法中),我最終會破壞props多次。

這是不好的做法嗎? 我是否應該將多次被this.propOfInterest = this.props.propOfInterestprop分配給實例本身(在constructor()類似this.propOfInterest = this.props.propOfInterest東西?

class MyComponent extends React.Component {
  myMethod() {
    const {
      propOfInterest,
    } = this.props

    // do something with propOfInterest
  }

  render() {
    const {
      propOfInterest,
    } = this.props

    return (
      <div className={propOfInterest}>
      </div>
    )
  }
}

進行銷毀不是一個壞習慣,並且不會以任何方式降低性能。 在后台,無論您是否進行銷毀,Babel都將在捆綁之前將您的代碼轉換為同一條語句。

所以基本上

const { propOfInterest } = this.props;

const propOfInterest = this.props.propOfInterest;

將以相同的方式捆綁在一起。

如果將這兩行復制到在線Babel轉譯器中 ,您將得到這些結果。

const { propOfInterest } = props;
const propInterest = props.propInterest;

將導致

var _props = props,
    propOfInterest = _props.propOfInterest;
var propInterest = props.propInterest;

談到性能,使用this的那一刻,它就成為一個實例變量。 根據尼古拉斯·扎卡斯Nicholas Zakas)在他的《 高性能JavaScript》一書中的描述,理想情況下實例變量在性能上要慢一些。

當涉及到Javascript數據時,幾乎有四種訪問它的方法:文字值,變量,對象屬性和數組項。 考慮優化時,文字值和變量的性能大致相同,並且比對象屬性和數組項快得多。

因此,無論何時多次引用對象屬性或數組項,都可以通過定義變量來提高性能。 (這適用於讀取和寫入數據。)

從作者的觀點得出結論,解構比將值存儲在實例變量中要快得多。

如果我們可以創建一個jsperf示例,我們肯定會知道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM