我正在尝试从firestore获取数据并将其显示在我的应用程序上,它工作得很好。但是,它不能从cacheImage组件显示我的图像。我的cacheimage在另一个组件(flatlist)上工作得很好,但它在我的个人资料页面上不起作用。这是我从firestore获取数据的代码
useEffect(
() => {
const unsubscribe = firebase
.firestore()
.collection(type)
.doc(id)
.onSnapshot(
doc => {
setLoading(false)
setDisplayData(doc.data())
},
err => {
setError(err)
}
)
return () => unsubscribe()
}, [id])
return (
<View style={{styles.container}}>
<CacheImage style={styles.imageStyle} image={displayData.avatar} width={'100%'}
height={300}>
</CacheImage>它是我的缓存图像组件(在其他页面中可以正常工作)
import React, { useState, useEffect } from 'react';
import { Image, View } from 'react-native'
import * as FileSystem from 'expo-file-system';
import md5 from 'md5'
export default CacaheImage = ({image,width,height}) => {
const [failed, setFailed] = useState(false)
const [imgUri, setImgUri] = useState()
useEffect(()=>{
console.log('image',image)
_DownLoadImage = async () => {
const img = image
const fileUri = FileSystem.documentDirectory + md5(image)+ '.jpg';
const info = await FileSystem.getInfoAsync(fileUri)
if (!info.exists) {
FileSystem.downloadAsync(
img,
fileUri,
).then(({ uri }) => {
console.log('Finished downloading to ', uri);
setImgUri({uri: uri})
})
.catch(error => {
console.error(error);
setFailed(true)
});
} else {
setImgUri({uri: info.uri})
console.log('exist')
}
}
_DownLoadImage()
},[])
return (
<View style={{borderRadius:10}}>
<Image style={{ width: width, height: height, borderRadius:10 }} source={imgUri}></Image>
</View>
);
}我想这是因为我的组件中有一个useEffect,它影响我从useEffect函数传递数据。
谢谢!
发布于 2019-12-10 07:08:08
我猜你要么想用
setImgUri(info.uri)或
source={imgUri.uri}因为您当前将imgUri设置为一个对象,所以这可能不是一个有效的source,除非您的代码中有一些东西没有显示给我们。
您可能还需要向useEffect的第二个参数添加依赖项,而不是空数组。我看到您在工作示例中使用了[id]。如果没有依赖关系,这将只在初始安装时运行,之后再也不会运行。
https://stackoverflow.com/questions/59256271
复制相似问题