Redux higher order components same as container components

安稳与你 提交于 2019-12-06 16:06:59

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.

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();
        }
    }
}

or compose the wrapped component:

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.


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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!