[英]React, setState warning for mounted/unmounted component
我有一个React组件,用于为我的应用程序逐步加载图像,这对我来说一直很好。 但是,当我在页面上使用它加载图像时,我看到一个错误:
warning.js:35警告:setState(...):只能更新已安装或正在安装的组件。 这通常意味着您在未安装的组件上调用了setState()。 这是无人值守。
多次-对于每个调用的图像来说,看起来就像一次。 由于图像组件仍在工作,它似乎并没有严重影响任何事情。 我想知道如何摆脱此错误,但我不知道如何解决。
所以这是我的组件:
import React, { PropTypes } from '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 for 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,
};
因此,只有在调用onLoad
或componentDidUpdate
时才调用setState。 我的想法是,因为它仅被调用完成安装和更新,所以不会出现此错误。 寻找有关如何清除此错误的任何见解,这让我感到困惑。 如果需要任何其他信息,我很乐意提供。
问题是您可以在任意随机点调用image.onload
的回调:
image.onload = this.onLoad;
可能是this.onLoad
在组件渲染时被调用。
问题是,因为this.onLoad
当你的外在形象资源负载那么当你正在做的是叫做this.setState
,您的组件可以被渲染, 这将导致该错误 。
为了解决这个问题,我建议在本地Component
状态之外设置loaded
/ image
值,而使用redux
类的方法dispatch
其dispatch
到全局状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.