【发布时间】:2021-03-16 11:13:14
【问题描述】:
我尝试在等待所有图像完全加载时制作加载屏幕。
React 生命周期是 Render -> componentDidMount -> 渲染,我的图像没有完全加载,刚刚被调用,但我的 componentDidMount 总是完成并执行渲染,即使我的图像没有完全加载。
componentDidMount() {
const ie = [document.querySelectorAll('img')];
ie.map(imgElm => {
for (const img of imgElm) {
if (!img.complete) {
this.setState({ imageIsReady : true});
}
}
return this.setState({ imageIsReady : false});
})
}
在componentDidMountfor循环函数上尝试检查每个img是否完整,给我一百个true(我的图像很多,只是尝试制作画廊)。和加载屏幕显示,但只有几毫秒,然后我可以滚动我的图像,但我的图像的一半以上仍在加载。
render() {
<div>
{
this.state.imageIsReady ?
<div className='inset-0 fixed flex justify-center z-20 w-full h-full bg-black bg-opacity-25 blur'>
<img src={loading} className='w-3/12' alt="load"/>
</div> :
<div className='hidden '>
<img src={loading} alt="load"/>
</div>
}
<div>page......</div>
</div>
}
我的代码:https://alfianahar.github.io/MobileLegendHeroList/ 在这个网站上我在我的componentDidMount 上使用setTimeout,这并不能解决我使用慢速 3g 和快速 3g 时的问题/
【问题讨论】:
-
你为什么在
const ie = [document.querySelectorAll('img')];中加上[]? -
@ShivamJha 因为如果我没有使用
[ ]包围,则地图将不起作用(即,如果我输入[ ],则成为数组),我试图删除它之前和TypeError: ie.map is not a function显示。
标签: javascript reactjs jsx