[英]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.