原文:Container Components

Container Components

在 React 模式上对我的代码有最深远影响的一个模式叫 container component 模式。

在 React.js Conf 上,Jason Bonta 和我们讲了他们在Facebook上是如何建立高性能组件(High Performance Components)。Nestled 在这个演讲中讲的就是this gem about container components

这个概念很简单:

一个 container 只是做数据拉取然后渲染与它的 corresponding 子组件。就是这样。

“Corresponding” 意味着分享同一个名称的组件,例如:

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

这就是其中的概念。

Why containers?

比如你有一个用于展示评论的组件。你并不知道有关 container 组件。所以,你会将所有东西都放在一个地方。

//  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});
}.bind(this)
});
} render(){
return <ul> {this.state.comments.map(renderComponent)} </ul>;
} renderComponent({body, author}){
return <li> {body}-{author} </li>;
}
}

你的组件就是用于拉取数据并展示它。这并没有什么"错误",但是你却错过了一些React的优点。

可复用性

CommentList组件除了在同一精确的条件情况下才能复用。

数据结构

你希望的组件应该规定他们需要的数据类型的预期。PropTypes正是干这个的。

我们的组件对数据结构要求很高但是没有办法说出这些要求。如果json的接口数据改变了,这个组件会不做出任何提示出错。(其实想说的就是,无法好好利用PropTypes来把控数据结构是否正确)

再来一次。这一次加上container

首先,让我们将数据拉取的功能移到 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} />;
}
}

现在,我们将comments作为CommentList的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并且一旦出错便会提示。

我是一个 container components 的大粉丝。他们让我的 React game 进步了很多,并且使我的组件更容易去阅读。尝试一下他们,并看一下Jason的演讲。太棒了!

Carry on, nerds.

(翻译)React Container Components的更多相关文章

  1. (翻译) Container Components

    react.js javascript   这篇文章翻译自Medium的一篇文章:Container Components 选择这篇文章翻译的原因是,在刚接触React的时候,这篇文章很好的指引我了解 ...

  2. [Redux] Extracting Container Components (FilterLink)

    Learn how to avoid the boilerplate of passing the props down the intermediate components by introduc ...

  3. Presentational and Container Components

    https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0 There’s a simple pattern I fi ...

  4. [Redux] Extracting Container Components -- Complete

    Clean TodoApp Component, it doesn't need to receive any props from the top level component: const To ...

  5. [Redux] Extracting Container Components -- VisibleTodoList

    Code to be refacted: const TodoList = ({ todos, onTodoClick }) => ( <ul> {todos.map(todo =& ...

  6. [React] Use React.ReactNode for the children prop in React TypeScript components and Render Props

    Because @types/react has to expose all its internal types, there can be a lot of confusion over how ...

  7. Tomcat翻译--Context Container

    原文:http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Resource_Definitions The Context Cont ...

  8. [Redux] Redux: Extracting Container Components -- AddTodo

    Code to be refactored: const AddTodo = ({ onAddClick }) => { let input; return ( <div> < ...

  9. React组件Components的两种表示方式

    函数式的表示: function Welcome(props) { return <h1>Hello, {props.name}</h1>; } Class式的表示: clas ...

随机推荐

  1. 基于Oracle的SQL优化(崔华著)-整理笔记-第2章“Oracle里的执行计划”

    详细介绍了Oracle数据里与执行计划有关的各个方面的内容,包括执行计划的含义,加何查看执行计划,如何得到目标SQL真实的执行计划,如何查看执行计划的执行顺序,Oracle数据库里各种常见的执行计划的 ...

  2. android adapter的性能小结

    一般adapter的做法会重写getView方法 比如 @Override public View getView(int position, View convertView, ViewGroup ...

  3. prototype原型模式

    /** * 原型模式 Prototype * 用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象 */ 需求: public class Resume { /** * 要求:一个简历类,必须 ...

  4. 判断是否是iPhone5

    #define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ...

  5. JS数组中级+高级技巧

    本文介绍JS数组一些比较进阶的方法: reverse:数组反转: join:(参数)以参数为连接符将数组拼接为字符串: 实例: var arr=[]; arr[3]="haha"; ...

  6. python爬虫错误

    错误描述 TypeError: list indices must be integers or slices, not str 错误缘由 取标签属性的时候, find_all()函数与find()函 ...

  7. 【转载】一张表看懂LTE和5G NR的区别

    转自:微信公众号:网优雇佣军 KPI 物理层

  8. Python3.x datetime模块

    1.时间间隔(timedelta) 指定时间长度之间计算差值 #!/usr/bin/env python __author__ = 'realtiger' """ @ve ...

  9. .NET4.0中使用4.5中的 async/await 功能实现异步

    在.NET Framework 4.5中添加了新的异步操作库,但是在.NET Framework 4.0中却无法使用.这时不免面临着抉择,到底是升级整个解决方案还是不使用呢? 如果你的软件还没发布出去 ...

  10. cratedb nodejs 试用

    安装cratedb docker run -d -p 4200:4200 crate nodejs 项目初始化 yarn yarn init -y 添加依赖 yarn add node-crate 基 ...