首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React Hooks UseEffect在我的cacheImage组件上不起作用

React Hooks UseEffect在我的cacheImage组件上不起作用
EN

Stack Overflow用户
提问于 2019-12-10 04:41:37
回答 1查看 867关注 0票数 0

我正在尝试从firestore获取数据并将其显示在我的应用程序上,它工作得很好。但是,它不能从cacheImage组件显示我的图像。我的cacheimage在另一个组件(flatlist)上工作得很好,但它在我的个人资料页面上不起作用。这是我从firestore获取数据的代码

代码语言:javascript
运行
复制
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>

它是我的缓存图像组件(在其他页面中可以正常工作)

代码语言:javascript
运行
复制
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函数传递数据。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2019-12-10 07:08:08

我猜你要么想用

代码语言:javascript
运行
复制
setImgUri(info.uri)

代码语言:javascript
运行
复制
source={imgUri.uri}

因为您当前将imgUri设置为一个对象,所以这可能不是一个有效的source,除非您的代码中有一些东西没有显示给我们。

您可能还需要向useEffect的第二个参数添加依赖项,而不是空数组。我看到您在工作示例中使用了[id]。如果没有依赖关系,这将只在初始安装时运行,之后再也不会运行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59256271

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档