reactjs - Avoid children re-render when component props change? -
i'm using react why-did-you-update node package, warns me when re-render avoidable.
and following code example
import react, {component, proptypes} 'react'; export default class testcomponent extends component { render() { const style = { marginleft: this.props.offset * 5 }; return ( <div style={style}> {this.props.children} </div> ) } } testcomponent.proptypes = { offset: proptypes.number, }; testcomponent.defaultprops = { offset: 0 };
i'm using component :
<testcomponent offset={this.state.offset}> <p>a lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </testcomponent >
when offset
props changed, got 3 warning why-did-you-update package, telling children re-render avoidable, see following screenshot
why-did-you-update console output
as can see, testcomponent had re-rendered because offset
props determines marginleft
style property, know if can avoid children re-render in order remove why-did-you-update warning in case ?
thanks !
Comments
Post a Comment