Redux 高阶组件与容器组件相同 [英] Redux higher order components same as container components

查看:52
本文介绍了Redux 高阶组件与容器组件相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试围绕高阶组件进行思考,这些组件是否与 Redux 容器组件相同.另外,编写高阶组件(容器组件)的推荐方法是通过扩展 React.Component 的类或不使用 redux 站点中给出的类.

I'm trying to wrap my head around higher order components, are these the same as Redux container components. Plus what is the recommended way to write higher order components (container components) is it through a class that extends React.Component or without one as given in the redux site.

推荐答案

关于这个主题写了这么多,所以我将尝试简要解释这个概念以及它与 Redux 的关系.

There's so much written on the subject, so I'll just try to briefly explain the concept and how it is related to Redux.

您可以将 HOC 视为增强器(或装饰器").它接受一个现有组件并返回一个新的、改进的组件.常见的任务是:注入道具、组合、改变渲染方式等.

You could think of HOC as an enhancer (or "decorator"). It takes an existing component and returns a new, improved one. Common tasks would be: injecting props, composing, changing the way it renders etc.

它通常作为一个函数来实现:获取一个组件,生成另一个组件.模式可能因您的目标和需求而异.

It is typically implemented as a function: getting one component, producing another. The pattern may vary depends on your goal and needs.

您可以扩展包装的组件:

You could extend the wrapped component:

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

如果您想保持简单并且不需要完整的生命周期,您还可以使用无状态组件:

and if you want to keep things simple and don't require the full life-cycle, you could also use a stateless component:

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

我建议阅读这个 更深入的了解.

I suggest reading this for a deeper understanding.

现在,这个概念没有与 Redux 结合,但 Redux 确实使用了它.
connect() 实际上是一个 HOC,它在被包裹的组件和 store 之间进行接线(注入 props 并负责重新渲染).它接受你的展示组件并返回一个连接的组件.
容器(连接")组件实际上是增强组件.

Now, this concept is not coupled with Redux, but Redux does use it.
connect() is actually a HOC that does the wiring between the wrapped component and the store (injects props and responsible for re-rendering). It takes your presentational component and returns a connected component.
Container ("connected") components are in fact enhanced components.

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

So to make it clear: Post is a component, we use the HOC connect() to create the enhanced component PostContainer.

这篇关于Redux 高阶组件与容器组件相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆