首页 > 解决方案 > 如何使加载屏幕运行直到所有图像都加载完毕?

问题描述

我尝试在等待所有图像完全加载时制作加载屏幕。React 生命周期是渲染 -> 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>
}

我的代码:httpssetTimeout ://alfianahar.github.io/MobileLegendHeroList/ 在我使用的这个站点中componentDidMount,这并不能解决我使用慢速 3g 或快速 3g/ 时的问题

标签: javascriptreactjsjsx

解决方案


也许这个例子可以帮助你。但请记住,这仅适用于未嵌套在组件内的图像。

class Component extends Component {
  constructor(props) {
      super(props)
      this.state = {
          ready: false
      }
  }

  componentDidMount() { 
      Promise.all(
          Array.from(document.images)
              .filter(img => !img.complete)
              .map(img => new Promise(
                  resolve => { img.onload = img.onerror = resolve; }
              ))).then(() => {
                  this.setState({ ready: true })
              });
  }


  render() {
      if ( ! this.state.ready ) return <div>Loader</div>

      return <div>Content</div>
  }
}
<Container>
    <img/> <!-- work -->
    <Component>
        <img/> <!-- doesn't work -->
    </Component>
</Container>

推荐阅读