从Firestore收到图像时如何等待承诺?



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

我尝试在检索时将 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>
);
}

上面的代码是我的最新尝试,由于返回了承诺而不是字符串 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.

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

您正在将async/await的使用与then()方法混合使用。

通过执行以下操作:

async getImg(user_id) {
const userSnapshot = await firebase.firestore().collection('User').doc(user_id).get()
return userSnapshot.data().image;
}

您将声明一个异步getImg()函数。

我不知道反应原生,所以我不知道它是否可以在

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

但是@VolkanSahin45解决方案(按如下方式调整(应该有效:

async getImg(user_id) {
const userSnapshot = await firebase.firestore().collection('User').doc(user_id).get()
this.setState({
img: userSnapshot.data().image;
})
}

请注意,最好按如下方式处理try/catch错误:

async getImg(user_id) {
try {
const userSnapshot = await firebase.firestore().collection('User').doc(user_id).get()
this.setState({
img: userSnapshot.data().image;
})
} catch (error) {
this.setState({
img: 'default_user_img.png';
})
}
}

getImg 函数返回 Promise。相反,您可以将 img 保存到状态并在有 img 时呈现。

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>
)
}

最新更新