javascript - Why HOC are applied during exporting of component in place of importing it -
my basic understading hoc connect (for connecting redux store) , other hoc's applied component while exporting it.
like this
import react, { component } 'react'; import './app.css'; import myhoc './myhoc/index'; class app extends component { render() { return ( <div classname="app"> </div>); } } export default myhoc({})(app);
where better thing apply hoc during import make easier make reusable component. same component can pick props store or props , responsibility of parent component check give hoc apply on component.
i know can use container components takes component , render children adds code in jsx (wont if there many container components)
though can this
import react, { component } 'react'; import './app.css'; import myhoc './myhoc/index'; import appchild './appchild'; const newappchild = myhoc({}, ()=> { })(appchild); class app extends component { state = { count: 1, }; rerender = () => { this.setstate({count: this.state.count + 1}); }; render() { return ( <div classname="app"> <newappchild handleclick={this.rerender} count={this.state.count}/> </div> ); } } export default app;
what question that, there better can handle kind of situations want apply hoc on import each many container components can import , can apply different hocs depending on needs.
there no single concrete reason design choice - have seen can invoke hoc wherever use component - see @ least 1 advantage: configuration & component reuse.
in example, myhoc
takes no parameters or configuration doesn't apply, imagine instead invoking connect
redux.
in use cases, connect
accepts 2 configuration functions - mapstatetoprops
& mapdispatchtoprops
- define behaviour. if define within mycomponent
consuming component can import mycomponent 'mycomponent'
, start using it.
if instead rely on parent component call connect()
forcing every consumer re-implement configuration of connect
well. may mean many instances of duplicated configuration , adds complexity consuming components.
that being said, there cases might want behaviour - example, if wanted connect
same component different state definitions. need pick best pattern support need component.
Comments
Post a Comment