【问题标题】:How can I create a Container component in React-Redux如何在 React-Redux 中创建容器组件
【发布时间】:2020-02-03 07:01:26
【问题描述】:

我构建了多个组件,每个组件都使用connect(mapStateToProps, mapDispatchToProps) 从存储和调度操作中检索数据。我想将它们全部组合在一个容器中并使用该容器。

例如:

主页组件

class Home extends React.Component{

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

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

购物车组件

class Cart extends React.Component{

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

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

所以,在这里我想将它们结合起来,并使用一个容器传递每个组件。

【问题讨论】:

  • 太好了,你试过什么?
  • 这可以使用 HOC 来完成。您是否尝试过创建一个?
  • 不,我没有使用任何高阶组件。你能帮我创建一个吗?
  • 我尝试创建 HomeContainer 类并尝试将 mapStateToProps 移动到该类中并在 Home 组件中使用该类的导入,但我在如何将道具从容器传递到类组件上陷入了困境。

标签: reactjs react-redux


【解决方案1】:

您可以通过仅在ContainerComponent 上使用redux-store 连接函数来执行此操作,并将容器从商店接收到的每个子道具传递给。

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>
}

【讨论】:

  • 嗨 Yves Kipondo,我如何在类组件中使用传递给 Child2Component 的那些道具。我正在尝试通过 this.props.items 访问它们。对吗?
  • 你能否建议我如何使用容器调度操作。
  • 这正是使用该道具的正确方法。调度动作的使用方式与道具完全相同
猜你喜欢
  • 2017-07-06
  • 2019-07-08
  • 2015-12-14
  • 1970-01-01
  • 2016-10-18
  • 2016-12-28
  • 2017-09-10
  • 1970-01-01
  • 2017-06-13
相关资源
最近更新 更多