2017-04-14 55 views

回答

15

Component是React API的一部分。组件是描述React UI的一部分的类或函数。

容器是React组件的一个非正式术语,它是connect - 已转至redux存储库。容器接收Redux状态更新和dispatch操作,并且它们通常不会呈现DOM元素;他们将代表呈现给呈现子组件。

欲了解更多详情,请阅读Dan Abramov的presentational vs container components

+0

这是一个很好的解释。非常简短,我可以得到细节 –

0

它们都是组件;容器是功能性的,所以它们不会自己渲染任何html,然后你也有表示组件,在那里你写出实际的html。容器的目的是将状态和派送映射到表示组件的道具。

进一步阅读:Link

0

的组件构建视图的我喜欢,所以它应该呈现的DOM元素,把内容在屏幕上。

容器参与数据阐述,因此它应该与redux“交谈”,因为它需要修改状态。所以,你应该包括连接(反应 - 终极版)是什么使得连接和功能mapStateToPropsmapDispatchToProps

. 
. 
. 
import { connect } from "react-redux"; 

class myContainer extends Component { 
} 

function mapStateToProps(state) { 
    // You return what it will show up as props of myContainer 
    return { 
    property: this.state.property 
    }; 
} 

function mapDispatchToProps(dispatch) { 
    // Whenever property is called, it should be passed to all reducers 
    return bindActionCreators({ property: property }, dispatch); 
} 

export default connect(mapStateToProps, mapDispatchToProps)(myContainer); 
1

反应,终极版是独立的库。

React为您提供了创建HTML文档的框架。组件以某种方式代表文档的特定部分。然后,与组件关联的方法可以操作文档的特定部分。

Redux是一个框架,它规定了一个特定的philosphy用于存储和管理JS环境中的数据。它是定义了特定方法的一个大JS对象,最好的用例是以Web应用程序的状态管理的形式出现的。

由于React规定所有数据都应该从根部流向叶片,因此将所有道具组装起来非常繁琐,定义组件中的道具并将道具传递给儿童。它也使整个应用程序状态变得脆弱。

通过简单地将连接的组件包装在另一个React组件(您的Container)周围,React Redux提供了一个干净的解决方案,它直接将您连接到Redux商店。由于在你的实现中,你的实现已经定义了你需要的整个应用程序状态中的哪一部分。因此,connect将这些数据从存储中取出,并将其作为道具传递给它周围环绕的组件。

考虑这个简单的例子:

class Person extends Component { 
    constructor(props){ 
    this.name = this.props.name; 
    this.type = this.props.type; 
    } 

    render() { 
    return <p> My name is {this.name}. I am a doctor { this.type } </p> 
    } 
} 

const connect = InnerComponent => { 

    class A extends Component{ 
    render() { 
     return <InnerComponent {...this.props} type="Doctor"/> 
    } 
    } 
    A.displayName = `Connect(${InnerComponent.displayName})` 
    return A 
} 

connect函数传递道具type

这种方式一个连接充当Person组件的容器。

相关问题