我有 2 个组件,我希望第 3 个组件在等待第 2 个组件加载图像时显示动画

I have 2 components and I want a 3rd component to show animation while waiting for the 2nd one to load images

import React from 'react';

const ImageList = ({ image }) => {
  const imgs = image.map(img => (
    <img
      key={img.id}
      src={img.urls.regular}
    />
  ));
  return (
    <div>
      {' '}
      {imgs}
      {' '}
    </div>
  );
};

export default ImageList;

我想添加另一个组件,在等待它获取图像时显示动画。

首先,你需要一个Loader组件来展示,我建议你自己建一个,但是有很多可用的,比如react-loading

要使用您的组件进行设置:

  • npm install react-loading
  • 然后,将您的组件替换为:
import React from 'react';
import ReactLoading from 'react-loading';

const ImageList = ({ image, loadingImages }) => {
  if(loadingImages){
    return <ReactLoading type={'spin'} color={'blue'} height={667} width={375} />
  }

  const imgs = image.map(img => (
    <img
      key={img.id}
      src={img.urls.regular}
    />
  ));
  return (
    <div>
      {' '}
      {imgs}
      {' '}
    </div>
  );
};

export default ImageList;
  • 在父组件中,将默认属性 loadingImages 设置为 true 在您所在的州,例如:
state = {
  loadingImages: true,
}
  • Fetch 函数的末尾,您实际使用对 setState 传递给此组件的图像的响应,还包括:
this.setState({
  images: response.data, //possibly how you do it
  loadingImages: false
})

看看这是否是您正在寻找的模式...

function getImagesMockAPI() {
  return new Promise((resolve, reject) => {
    setTimeout(()=>resolve(['Image1', 'Image2', 'Image3']),3000);
  });
}

function App() {
  const [loading, setLoading] = React.useState(true);
  const [images, setImages] = React.useState(null);
  
  React.useEffect(()=>{
  
  getImagesMockAPI()
  .then((data)=> {
    setImages(data);
    setLoading(false);
  });
  
  },[]);
  
  return(
    loading ? 
      <div>Loading images (I could be a Spinner)...</div>
    : <div>{JSON.stringify(images)}</div>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>