Enhancers

Example

let foo = (....) => {...}

let enhancer = (aF, bF) => (p) => p(foo(aF, bF))
let container = enhancer(aF,bF)
let component = container(presenter) // <Presenter {...foo(aF, bF)}/>

For instance, connect in redux

let operation = (ms, md, store, ownProps) => {
    let p1 = ms(store.getState(), ownProps);
    let p2 = md(store.dispatch, ownProps);
    return {...p1, ...p2, ...ownProps}
}

let connect = (mapState, mapDispatch) => {
    let ps = operation(mapState, mapDispatch, store)
    return (component) => {
        return component({...ps, ...component.props})
    }
}

const mapStateToProps = (state, ownProps) => {...}
const mapDispatchToProps = (dispatch, ownProps) => {...}

let container = connect(mapStateToProps, mapDispatchToProps);

const presenter = (props) => (<SomeLayout/>);

let component = container(presenter)
  1. connect is an higher-order function provided by redux, in which stateless components are preferred due to a number of reasons. Some people also call this enhancer.
  2. connect is designed to be reusable for cases that
    1. state has to be injected to a stateless component in form of prop , or
    2. actioncreator that also in form of prop has to be dispatched to reducer,
    3. and in fact, 95% of redux components are working in this way, thus it is highly reusable.
  3. With specific mapSthToProps is provided to connect, this enhancer will produce another higher-order function that ready to bind with presenter. This subsequent HOF is called container.
    1. container is reusable when mapSthToProps is shared
    2. test on business logic should be asserted in this layer
  4. Once the stateless presenter is bound to container, the missing props are accomplished. Through the input-process-output routine implemented inside a functional component, UI would be rendered
    1. this final component is a real component that returning UI
    2. we often call this higher-order components
    3. test on presentation should be asserted in this layer

Reference

results matching ""

    No results matching ""