javascript - Difference between decorators and mixins in react -


i beginner react , finding myself confused between mixin , decorators. can elaborate? thanks.

they both extend and/or override methods of react component. used share common functionality between components, in places extending class not work , not intended.

an example purerendermixin, overrides shouldcomponentupdate method , compares props of component decide, if rerender should executed.

however, mixins deprecated , not work es6 syntax of react anymore. options either use inheritance or decorators achieve same result.

example

here example of (kind of) purerendermixin, using decorator. used immutable.js.

// pure.js import react 'react'; import assign 'object-assign'; import {is} 'immutable';  /**  * pure render decorator  * @param props  * @returns {function()}  */ export default (...props) => (component) => class purecomponent extends react.component {      shouldcomponentupdate(nextprops) {         if (!props.length) {             props = object.keys(nextprops);         }         (let = 0, l = props.length; < l; i++) {             if (!is(nextprops[props[i]], this.props[props[i]])) {                 return true;             }         }         return false;     }      render() {         return react.createelement(component, assign({},             this.props,             this.state         ));     } } 

the general usage of decorator @pure(params). params can contain name of props or can empty. in decorator see ...props parameter. params passed in.

the parameter component of inner function gets react component passed in, on use decorator.

you can use decorator in component follows:

import react 'react'; import pure './pure.js';  @pure('myprop', 'anotherprop') export default mycomponent extends react.component {      static proptypes = {         myprop: react.proptypes.any,         anotherprop: react.proptypes.any     }      render() {         return <p>i re-render, when props changed.</p>;     }  } 

what do?

the decorator overrides shouldcomponentupdate method of component. everytime react component calls shouldcomponentupdate method, uses 1 provided in decorator.

the decorator compares props of component next props going receive. if props change, component update. nice, because prevents unnecessary rendering - that's great performance!

you see, decorators functions take parameters (such react component) , modify them in order make code reusable. takes bit of getting used to, no rocket science. :-)

if there more questions, please feel free ask!


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -