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.
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
.
来源:https://stackoverflow.com/questions/42307736/redux-higher-order-components-same-as-container-components