首页 文章

映射Firebase中的图像列表并将其显示在React组件中

提问于
浏览
1

我有已上传到Firebase存储的图像,我想再次下载它们以在组件中呈现它们 . 我在Firebase实时数据库中保存了一个名称列表,以便我可以使用这些名称从Firebase存储中检索图像 .

在componentDidMount中,我正在检索图像,然后将它们作为数组保存到this.state . 当我尝试在渲染函数中映射数组时,没有任何反应 . 如果我是console.log(this.state.images),我看到了数组,但我无法映射它以呈现它 .

export default class Images extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();

  }

  componentDidMount() {
    this.unsubscribe = store.subscribe(() => {
      this.setState(store.getState());
    });
    let photos = [];
    database
      .ref("images/")
      .once("value")
      .then(function(snapshot) {
        let values = snapshot.val();
        let images = [];

        for (var key in values) {
          images.push(values[key]["filename"]);
        }
        images.map(image => {
          // Create a reference to the file we want to download
          const storageRef = storage.ref();
          // Get the download URL
          storageRef
            .child("images/" + image)
            .getDownloadURL()
            .then(function(url) {
              // Insert url into an <img> tag to "download"
              photos.push(url);
            })
            .catch(function(error) {
              // A full list of error codes is available at
              // https://firebase.google.com/docs/storage/web/handle-errors
              switch (error.code) {
                case "storage/object_not_found":
                  // File doesn't exist
                  break;

                case "storage/unauthorized":
                  // User doesn't have permission to access the object
                  break;

                case "storage/canceled":
                  // User canceled the upload
                  break;
                case "storage/unknown":
                  // Unknown error occurred, inspect the server
                  break;
              }
            });
        });

      });
      this.setState({ images: photos})
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    return (
      <div>

       {this.state.images && this.state.images.map(image => {
         console.log(image)
       })
       }
        </div>
    )
  }
}

1 回答

  • 1

    您的代码中有许多不必要的重定向 . 您不需要使用 forceUpdate() 来显示React组件中的图像列表 .

    • 在状态中创建一个空间来存储图像

    state = { images: null }

    • 获取图像URL并将其存储在状态中 .

    componentDidMount() { database .ref("images/") .once("value") .then(snap => this.setState({images: snapshot.val()}) .catch(error => console.error(error)) }

    • 当URL在状态下可用时,映射URL并在图像标记中呈现每个URL,就像您所做的那样 .

    render() { return ( <div> {this.state.images && this.state.images.map((image, index) => { <img src={image} key={index}/> })} </div> ) }

    数据库调用中发生的时髦存储参考舞蹈是完全没必要的 . 您应该首先将downloadURL存储在数据库中 . 如果您不是,请记录 this.state.images ,以便我们看到您存储在数据库中的内容 . 你只是说你已经存储了一个名单,我不明白你的意思 .

相关问题