【譯】容器組件 (Container Components)

medium 原文連接react

對個人代碼有最深遠影響的一個React模式叫 container component 模式。json

Jason Bonta 講了如何創建高性能組件(High Performance Components),這個演講講的就是 container components數據結構

這個概念很是簡單:oop

一個 container 僅僅只是作數據拉取而後渲染它對應的子組件。性能

「Corresponding」 意味着分享同一個名稱的組件,例如:fetch

(StockWidgetContainer) => StockWidget;
(TagCloudContainer) => TagCloud;
(PartyPooperListContainer) => PartyPooperList;
複製代碼

這就是其中的概念。this

Why containers?

假設你有一個用於展現評論的組件。在你不使用 container 組件的時候,你會把全部代碼都放在一個地方:spa

class CommentList extends React.Component {
  this.state = { comments: [] };

  componentDidMount() {
    fetchSomeComments(comments =>
      this.setState({ comments: comments }));
  }
  render() {
    return (
      <ul> {this.state.comments.map(c => ( <li>{c.body}—{c.author}</li> ))} </ul>
    );
  }
}
複製代碼

你的組件就是用於拉取數據並展現它。這並無什麼錯,可是你錯過了一些 React 的優勢。code

可複用性 (Reusability)

除非在徹底相同的狀況下,不然CommentList 組件沒法被複用。component

數據結構(Data structure)

你的標記組件應該給出他們所指望的數據類型。PropTypes就是作這個的。

咱們的組件對數據結構要求很高可是沒有辦法說出這些要求。若是 json 的接口數據改變了,這個組件會不作出任何提示出錯。(其實想說的就是,沒法好好利用 PropTypes 來把控數據結構是否正確)

用container重寫一遍 (Once again. This time with a container)

首先,咱們把數據拉取的功能放到 container 組件上。

class CommentListContainer extends React.Component {
  state = {
    comments: []
  };

  componentDidMount() {
    fetchSomeComments((comments) => this.setState({ comments: comments }));
  }

  render() {
    return <CommentList comments={this.state.comments} />; } } 複製代碼

如今,咱們修改CommentList讓它接收comments 做爲prop

const CommentList = (props) => (
  <ul> {props.comments.map((c) => ( <li> {c.body}—{c.author} </li> ))} </ul>
);
複製代碼

咱們學到了啥?(So, what did we get?)

咱們實際上獲得了不少...

咱們分離了數據拉取和渲染(data-fetching and rendering)。

咱們使咱們的 CommentList 組件得以複用。

咱們賦予了CommentList設置PropTypes和錯誤提示的能力。

我是一個container components的大粉絲。他們讓個人 React game 有了很大的進步,而且使個人組件更加易讀。試試,看看 Jason 的演講。太棒了!

Carry on, nerds.

——完——

相關文章
相關標籤/搜索