简体   繁体   English

如何在 React-Redux 中创建容器组件

[英]How can I create a Container component in React-Redux

I have multiple components built and each component is using connect(mapStateToProps, mapDispatchToProps) to retrieve data from the store and dispatch actions.我构建了多个组件,每个组件都使用connect(mapStateToProps, mapDispatchToProps)从存储和调度操作中检索数据。 I want to combine them all in a single container and use that container.我想将它们全部组合在一个容器中并使用该容器。

For ex:例如:

Home Component主页组件

class Home extends React.Component{

}
const mapStateToProps = (state) => {
    return {
        items: state.items
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        addToCart: (id) => {dispatch(addToCart(id))}
    }
}

and Cart Component购物车组件

class Cart extends React.Component{

}
const mapStateToProps = (state) => {
    return {
        items: state.items
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        addToCart: (id) => {dispatch(addToCart(id))}
    }
}

So, here I want to combine both of them and use a single container passed each of the components.所以,在这里我想将它们结合起来,并使用一个传递每个组件的容器。

You can perform that by use redux-store connect function only on the ContainerComponent and pass to each child props which the Container has receive from the store.您可以通过仅在ContainerComponent上使用redux-store连接函数来执行此操作,并将其传递给 Container 从商店接收的每个子道具。

const mapPropsToState = (state) => {
    items: state.items,
    // .... other properties
}
connect(mapPropsToState, mapDispatchToProps)(ContainerComponent);

export class ContainerComponent extends Component {
    render = () => <div>
        <Child2Component items={this.props.item} />
        <Child2Component items={this.props.item} />
        // .... other component which need to access props receive from Store
    </div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM