React.js: Functional Components vs Class-based Components

React.js

React 的元件可用以下方式分類

Functional Components

Functional Components 的撰寫方式是從父層傳遞的 props 得到資料,然後將結果 JSX 輸出至 DOM。

特點

範例

這個元件 VideoListItem 從父層得到 video,接著輸出一段 HTML,內含剛剛從 video 內得到的標題和圖檔位置。

const VideoListItem = ({ video }) => {
  return (
    <li>
      <h3>{video.title}</h3>
      <img src={video.imageUrl} />
    </li>
  );
};

Class-based Components

特點

範例

這個元件 SearchBar 是用來輸入欲搜尋的字串,未來會將這個字串丟到伺服器端以得到搜尋結果。

class SearchBar extends Component {
  // ----- (1)
  constructor(props) {
    super(props); // ----- (2)

    this.state = { term: '' }; // ----- (3)
    this.onInputChange = this.onInputChange.bind(this); // ----- (4)
  }

  render() {
    return (
      // ----- (5)
      <div>
        <input
          value={this.state.term} // ----- (6)
          onChange={this.onInputChange}
        />
      </div>
    );
  }

  onInputChange(event) {
    this.setState({ term: event.target.value }); // ----- (7)
  }
}

Pure Components

只要可以保證相同的輸入會得到相同的輸出,那麼就可以稱這個元件是 Pure Components。因此,Functional Components 是 Pure Components;而只要 props 和 state 是 Immutable,Class-based Components 也可以是 Pure Components。

React.PureComponentShouldComponentUpdate()React.ComponentShouldComponentUpdate() 不同之處在於,React.PureComponentShouldComponentUpdate() 只做淺比較(Shallow Compare),也就是只比較位置而不比較內容值,因此一但儲存的位置相同但內容不同,就無法正常運作。淺比較的運作基礎是假設資料是 Immutable,也就是說,只要資料更新就存到另一個記憶體位置,因此只要比對記憶體位置就等於比較值是否相等。

References


react.js