javascript - React, setState warning for mounted/unmounted component -
i have react component using load images progressively app has been working great me. when use on page load images, though, seeing error:
warning.js:35 warning: setstate(...): can update mounted or mounting component. means called setstate() on unmounted component. no-op.
multiple times - looks once each image called. not seem effecting image components still work. wondering how rid of error though, cannot figure out how.
so here component:
import react, { proptypes } 'react'; require('./progressive-image.scss'); export default class progressiveimage extends react.component { constructor(props) { super(props); this.state = { loaded: false, image: props.smallimg }; this.loadimage = this.loadimage.bind(this); this.onload = this.onload.bind(this); this.onerror = this.onerror.bind(this); this.image = undefined; } componentdidmount() { const { largeimg } = this.props; this.loadimage(largeimg); } onerror(err) { console.warn('error loading progressive image :', err); } onload() { this.setstate({ loaded: true, image: this.image.src }); } componentdidupdate(nextprops) { const { largeimg, smallimg } = nextprops; if (largeimg !== this.props.largeimg) { this.setstate({ loaded: false, image: smallimg }, () => { this.loadimage(largeimg); }); } } loadimage(src) { if (this.image) { this.image.onload = null; this.image.onerror = null; } const image = new image(); this.image = image; image.onload = this.onload; image.onerror = this.onerror; image.src = src; } render() { const imgstyle = { 'paddingbottom': this.props.heightratio }; const { imgalt, imgtitle } = this.props; return ( <div classname={`progressive-placeholder ${this.state.loaded ? 'loaded' : ''}`}> {this.state.loaded && <img alt={imgalt} classname={`loaded`} src={this.state.image} title={imgtitle} /> } <img classname={`img-small ${!this.state.loaded ? 'loaded' : ''}`} src={this.state.image} alt="placeholder image loading"/> <div style={imgstyle} ></div> </div> ); } } progressiveimage.displayname = 'progressiveimage'; progressiveimage.proptypes = { bgcolor: proptypes.string, heightratio: proptypes.string.isrequired, largeimg: proptypes.string.isrequired, smallimg: proptypes.string.isrequired, imgalt: proptypes.string, imgtitle: proptypes.string, };
so time setstate called when onload
or componentdidupdate
called. thinking because called did mount , did update should not getting error. looking insight on how clean error, has me puzzled. if additional info needed, happy provide.
the problem callback in image.onload
called @ any random point:
image.onload = this.onload;
chances this.onload
being called while component rendering.
the problem because this.onload
called when external image resource loads when doing this.setstate
, component rendering , this cause error.
to handle recommend setting loaded
/image
values outside of local component
state , instead dispatch
global state using redux
.
wiki
Comments
Post a Comment