(翻译) Container Components

这篇文章翻译自Medium的一篇文章:Container Components

挑选这篇文章翻译的原因是,在刚打仗React的时刻,这篇文章很好的指引我相识Container Components形式。

Container Component形式

Container components形式是一款很棒的React形式,对我的代码影响很大。

Jason Bonta在React.js大会中说过他们如安在Facebook开辟高效的组建。在这个演讲中,他提到了container components形式。

实在道理很简单:

一个container担任数据的猎取,然后衬着它对应的下级component。就这些罢了。

“对应的”的意义是他们具有配合的称号:

StockWidgetContainer => StockWidget
TagCloudContainer => TagCloud
PartyPooperListContainer => PartyPooperList

也许就是这个意义。

为何要用Containers呢?

假定我们须要做一个展现批评的组建。在你不知道container components形式之前,你会把一切的东西都放在一个内里:

// CommentList.js
class CommentList extends React.Component {
  constructor() {
    super();
    this.state = { comments: [] }
  }
  componentDidMount() {
    $.ajax({
      url: "/my-comments.json",
      dataType: 'json',
      success: function(comments) {
        this.setState({comments: comments});
      }.bind(this)
    });
  }
  render() {
    return <ul> {this.state.comments.map(renderComment)} </ul>;
  }
  renderComment({body, author}) {
    return <li>{body}—{author}</li>;
  }
}

你的这个组建要同时担任猎取数据和展现数据。固然,这类做法没有什么错的,然则你没有很好的应用React的一些上风。

复用性

除非在一个如出一辙的运用环境下,你没法重用CommentList组建。

数据构造

你的展现组建对须要的数据架构有详细的请求,而PropTypes能够很好地满足这个请求。
展现组建对数据构造有肯定的请求,然则却没有方法限定数据类型。假如传入的json构造发生了转变,那末组建就会down掉,并不会抛出任何毛病。

假如我们运用container

// CommentListContainer.js
class CommentListContainer extends React.Component {
  constructor() {
    super();
    this.state = { comments: [] }
  }
  componentDidMount() {
    $.ajax({
      url: "/my-comments.json",
      dataType: 'json',
      success: function(comments) {
        this.setState({comments: comments});
      }.bind(this)
    });
  }
  render() {
    return <CommentList comments={this.state.comments} />;
  }
}

同时,我们修正一下CommentList让它能够接收一个comments的prop。

// CommentList.js
class CommentList extends React.Component {
  constructor(props) {
    super(props);
  }
  render() { 
    return <ul> {this.props.comments.map(renderComment)} </ul>;
  }
  renderComment({body, author}) {
    return <li>{body}—{author}</li>;
  }
}

所以,我们这么做获得了什么?

我们猎取了许多东西…
我们分离了数据猎取和数据衬着的逻辑。
我们让CommentList变成了可复用的组建。
我们许可CommentList能够经由过程PropTypes来限定props数据个花样。假如props花样失足,就会报错。

我是container components形式的忠厚蜂拥者,它协助我更好的完成React项目。人人无妨试一试,也能够寓目这个视屏。一个很棒的形式。

再次声明:这篇文章翻译自Medium的一篇文章:Container Components
假如要转载,请最少有名上面的文章出处,感谢。

    原文作者:Clark
    原文地址: https://segmentfault.com/a/1190000007786080
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞