reactjs - React Hooks UseEffect 不适用于我的 cacheImage 组件
问题描述
我正在尝试从 firestore 获取数据并将其显示在我的应用程序上,它工作正常。但是,它无法从 cacheImage 组件中显示我的图像。我的 cacheimage 与另一个组件(平面列表)一起工作正常,但它在我的个人资料页面上不起作用。这是我从 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 函数传递数据。
谢谢!
解决方案
我猜你要么想用
setImgUri(info.uri)
或者
source={imgUri.uri}
由于您当前正在设置imgUri
一个对象,这可能不是有效的source
,除非您的代码中有某些内容您没有向我们展示。
您可能还需要将依赖项添加到第二个参数useEffect
而不是空数组。我看到你[id]
在你的工作示例中有。如果没有依赖项,这只会在初始安装时运行,之后再也不会运行。
推荐阅读
- python - 对于数据框中的每个组,删除满足某些条件的行之后的行
- regex - BASH:如何在 sed 命令中对字符串使用 Regex Negative Lookahead?
- node.js - 用户注册 - MEAN 堆栈 - 错误:非法参数:未定义,字符串
- google-apps-script - 编辑触发器未运行
- php - Codeigniter 未处理 Instagram 身份验证重定向中的问号
- python-3.x - 我试图从树莓派捕获数据包一秒钟以获得每秒数据包的比率
- php - 我需要在 laravel 中找零。对象到数组 {} 到 [](尝试区分 '[object Object] 时出错)
- python - 在负利率的 PV 公式中寻找期限
- python-3.x - 如何从python中的行号中获取短语?
- html - Bootstrap 对齐文本和图像