【译】容器组件 (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.

——完——

相关文章
相关标签/搜索