Ate*_*pra 5 javascript reactjs
我有一个react应用程序,其中使用另一个名为的组件加载图像load-image。
现在,我src转到load-image,它显示了一个不错的加载器,直到图像加载为止;加载时,它显示了一个很好的图像动画。
问题出现在这里。我打开了应用程序页面,所有图像开始加载。现在用户转到另一个页面,图像仍在加载。我可以看到它们正在控制台中加载。现在,我在控制台中收到此错误。
警告:setState(...):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了setState()。这是无人值守。请检查未定义组件的代码。
这是我的代码。
export default class LoadImage extends React.Component {
constructor() {
super();
this.state = {
isLoaded: false,
isMounted: false,
};
this.onImageLoad = this.onImageLoad.bind(this);
}
componentDidMount() {
const imgSrc = this.props.imageSrc;
const img = new window.Image();
img.onload = this.onImageLoad;
img.src = imgSrc;
this.setState({
isMounted: true,
});
}
componentWillUnmount() {
this.setState({
isMounted: false,
});
}
onImageLoad() {
const self = this;
if (self.state.isMounted === true) {
self.setState({
isLoaded: true,
});
}
}
render() {
const self = this;
const imageClasses = classNames({
'image-loaded': self.state.isLoaded,
'image': true,
});
const imgStyle = {
backgroundImage: 'url("' + self.props.imageSrc + '")',
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
width: 'inherit',
height: 'inherit',
};
return (
<div className="image-loader">
<div style={ imgStyle } className={ imageClasses }>
</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我如何取消较旧的请求,以便它们在卸载后不更新状态。我已经在使用状态来检查组件是否已安装。谢谢。
您可以在图像仍加载时更改回调。在中componentWillUnmount,设置this.img.onload为不执行任何操作的函数。
componentDidMount() {
const imgSrc = this.props.imageSrc;
this.img = new window.Image();
this.img.src = imgSrc;
this.img.onload = this.onImageLoad;
}
componentWillUnmount() {
if ( ! this.img ) {
return;
}
this.img.onload = function(){};
delete this.img;
}
Run Code Online (Sandbox Code Playgroud)
来源:https : //github.com/Automattic/wp-calypso/blob/master/client/components/image-preloader/index.jsx
如果采用这种方法,则不需要isMounted()。
| 归档时间: |
|
| 查看次数: |
1505 次 |
| 最近记录: |