Redux 高阶组件与容器组件相同

Redux higher order components same as container components

我正在思考高阶组件,它们与 Redux 容器组件是否相同。另外,编写高阶组件(容器组件)的推荐方法是通过扩展 React.Component 的 class 还是不使用 redux 站点中给出的方法。

so much 关于这个主题的文章,所以我将尝试简要解释一下这个概念以及它与 Redux 的关系。

您可以将 HOC 视为增强器(或 "decorator")。它需要一个现有组件和 returns 一个新的、改进的组件。常见的任务是:注入道具、组合、改变渲染方式等。

它通常作为一个函数实现:获取一个组件,生成另一个组件。模式可能会有所不同,具体取决于您的目标和需求。

您可以扩展包装的组件:

function hoc(WrappedComponent) {
    return class HOC extends WrappedComponent {
        render() {
            return super.render();
        }
    }
}

或编写包装组件:

function hoc(WrappedComponent) {
    return class HOC extends React.Component {
        render() {
            return (<WrappedComponent {...this.props} extraProp={1} />)
        }
    }
}

如果你想保持简单并且不需要完整的 life-cycle,你也可以使用无状态组件:

function hoc(WrappedComponent) {
    return (props) => (<WrappedComponent {...props} extraProp={1} />);
}

我建议阅读 this 以获得更深入的理解。


现在,这个概念没有与 Redux 耦合,但 Redux 使用它。
connect() 实际上是一个 HOC,它在包装组件和商店之间进行连接(注入 props 并负责 re-rendering)。它需要您的演示组件和 returns 连接的组件。
容器("connected")组件其实是增强组件.

所以说清楚:Post是一个组件,我们使用HOCconnect()创建增强组件PostContainer.