首页 > 解决方案 > 从 Firestore 接收图像时如何等待承诺?

问题描述

我正在使用 React Native 制作一个应用程序,并将有关用户的信息存储在 Firestore 上名为“User”的集合中。每个用户都有一个存储在集合中的个人资料图片 url,我想在同一页面上显示多个用户图像。然而,由于不得不等待 Promise 返回,我正在努力让它工作。

我尝试在检索时将 url 存储在状态变量中,但是,由于我要显示的图像数量,这将涉及创建状态变量的负载。然后我尝试使用 async/await 和 then 语句,但由于承诺没有及时返回,图像不会加载。

async getImg(user_id) {
    return await firebase.firestore().collection('User').doc(user_id).get()
        .then(user => {return user.data().image})
render() {

      <SafeAreaView style={styles.container}> 
          <Image source={{uri: this.getImg('rwWa39Y6xtS1nZguswugODWndqx2') }} style={{ ... }} />
          <Image source={{uri: this.getImg('HQkCoChUe5fkZrHypYdRnrw66Rp2') }} style={{ ... }} />

      </SafeAreaView>
    );

  }

上面的代码是我的最新尝试,由于返回的是 promise 而不是字符串 url,它返回以下错误。

You attempted to set the key `_65` with the value `1` on an object that is meant to be immutable and has been frozen.

有谁知道如何解决这个问题?

标签: javascriptfirebasereact-nativeasync-awaitgoogle-cloud-firestore

解决方案


getImg 函数返回 Promise。相反,如果有 img,您可以将 img 保存到 state 并渲染。

async getImg(user_id) {
  return await firebase.firestore().collection('User').doc(user_id).get()
    .then(user => {
        this.setState({
          img: user.data().image 
        })
      }
    )
}

render() {
  const { img } = this.state;
  return(
    <SafeAreaView style={styles.container}> 
      img && <Image source={{ img }} style={{ ... }} />
    </SafeAreaView>
  )
}

推荐阅读