延迟加载,显示图标或图像

时间:2019-04-04 03:12:37

标签: javascript reactjs

我正在等待显示图像(从AWS服务器下载)时显示组件。我知道在React世界中有什么好的做法。将图像调用移到子组件,或尝试在父组件中找到更好的方法。

这是我的代码:

子组件:

class PhotoTile extends React.Component{
  render(){
    const iconOrImg = () => {
      console.log(this.props.photo.urls)
      if(this.props.photo.urls !== undefined && this.props.photo.urls !== null && this.props.photo.urls !== ""){
        return (
          <img
            id= { this.props.photo.id }
            alt="buck"
            src={ this.props.photo.urls.medium }
          />
        )
      }else {
        return(
          <IconNoPhoto />
        )
      }

    }
    return (
      <div>
        {iconOrImg()}
      </div>
    );
  }
};

父组件:

class PhotoGallery extends React.Component {
  state = {
    photoTiles: [],
    alertIsOpen: false,
    alertText: "",
    alertTitle: ""
  };

  showPhoto = (photo) => {
    getPhoto(photo, "medium")
    .then(response => {
      let imgSrc = {urls: { medium: response}}
      Object.assign(photo, imgSrc);

    })
    .catch(() => {
      // TODO Add a better explanation to the error
      this.setState({ alertIsOpen: true })
    })
  };

  componentDidMount = () => {
    getPhotoList(this.props.cameraId)
      .then(photosList => {
        photosList.forEach(photo => {
          this.setState({
            photoTiles: [...this.state.photoTiles, <PhotoTile key={ photo.id } photo={ photo } />]
          })
          this.showPhoto(photo)
        });

      })
    .catch(() => {
      // TODO Add a better explanation to the error
      this.setState({ alertIsOpen: true })
    })
  };

  render() {
    const { t } = this.props
    return (
        <div style={{
          display:"flex",
          flexFlow:"wrap",
          marginTop: "1S65px"
          }}>
          {this.state.photoTiles}
          <Alert
            id="alert"
            text={ t('photo_gallery.error') }
            title={ this.state.alertTitle }
            open={ this.state.alertIsOpen }
            onClose={ () => this.setState({ alertIsOpen:false }) }
          />
        </div>

    );
  };
};

0 个答案:

没有答案