首页 > 解决方案 > 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 函数传递数据。

谢谢!

标签: reactjsreact-native

解决方案


我猜你要么想用

setImgUri(info.uri)

或者

source={imgUri.uri}

由于您当前正在设置imgUri一个对象,这可能不是有效的source,除非您的代码中有某些内容您没有向我们展示。

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


推荐阅读