【问题标题】:React Hooks UseEffect is not working on my cacheImage componentReact Hooks UseEffect 不适用于我的 cacheImage 组件
【发布时间】:2019-12-09 20:41:36
【问题描述】:

我正在尝试从 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 函数传递数据。

谢谢!

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    我猜你要么想用

    setImgUri(info.uri)
    

    source={imgUri.uri}
    

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

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

    【讨论】:

    • 这就是缓存组件和 useEffect 的所有代码,我只想进行初始调用。我想你可能在你指出的 imguri 上是对的。如您所见,我确实尝试了缓存图像组件的控制台日志,但它未定义
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2019-06-18
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多