【发布时间】:2016-12-15 02:39:07
【问题描述】:
我正在尝试创建一个加载背景图像的组件(在同构应用程序中)。在加载图像时,我想显示一个微调器,但是我一直遇到这个错误:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
在初始化时,加载状态设置为 false(因此如果 js 被禁用,它不会显示微调器)
constructor (props) {
super(props);
this.state = {
loading: false
};
}
在 componentDidMount 上,加载状态设置为 true,并使用 props.src 创建图像,并在加载或错误时调用函数。
componentDidMount = () => {
this.setState({loading: true});
this.image = new Image();
this.image.src = this.props.src;
this.image.onload = this.handleImageLoaded;
this.image.onerror = this.handleImageError;
}
这些函数会将加载状态设置为false
handleImageLoaded = () => {
this.setState({loading: false});
}
handleImageError = () => {
this.setState({loading: false});
}
如果 state 为 true(这会渲染),渲染函数将显示一个单独的组件 Loader,并且我将在 img 加载时更改内联样式背景。
return (
<div className={style.wrapper}>
<div className={style.background} style='background-image:'>
<Loader loading={this.state.loading} />
</div>
</div>
);
【问题讨论】:
-
可以发
Loader组件代码吗?
标签: javascript reactjs