React.js 中 useState 钩子的生命周期

时间:2021-07-01 10:47:00

标签: reactjs react-hooks state react-lifecycle

我有以下同步问题。鉴于我知道 React useState 钩子是异步的,我遇到以下情况:我正在从 Amazon S3 下载一些图像,我设法将其正确保存在我的钩子中:defaultSelfiePicture 并取决于图像的重量(或者我认为)有时我会正确加载图像,有时不会。在我将对象保存到钩子中后,我试图强制更改状态,但它永远不会渲染图像,只有当我更改组件并返回时才会在加载时间更长的情况下显示它。

const [defaultSelfiePictures, setDefaultSelfiePictures] = useState([])


useEffect(() => {
    if (savedUser.docs !== undefined) {         
        loadAllPictures()
    }
}, [savedUser.docs.length])

const loadAllPictures = () => {
    let p1 = loadUrlDefaultFrontPictures()
    let p2 = loadUrlDefaultBackPictures()
    let p3 = loadUrlDefaultSelfiePictures()

    Promise.all([p1, p2, p3]).then(result => {
        console.log('end all promises')
        setTimestamp(Date.now())
    })
}

const loadUrlDefaultSelfiePictures = async () => {
    if (savedUser.docs.length > 0) {
        let readedPictures = []
        for (let i = 0; i < savedUser.docs.length; i++) {
            if (
                savedUser.docs[i].type === 'SELFIE'
                //&&                    savedUser.docs[i].side === 'FRONT'
            ) {
                if (
                    savedUser.docs[i].s3Href !== null &&
                    savedUser.docs[i].s3Href !== undefined
                ) {
                    const paramsKeyArray =
                        savedUser.docs[i].s3Href.split('')
                    let paramsKey = paramsKeyArray.pop()

                    let params = {
                        Bucket: process.env.REACT_APP_S3_BUCKET,
                        Key: paramsKey
                    }

                    await s3.getSignedUrl('getObject', params, function (err, url) {
                        readedPictures.push({
                            idKycDoc: savedUser.docs[i].idKycDoc,
                            name: 'selfie.jpeg',
                            type: savedUser.docs[i].type,
                            url: url
                        })
                    })

                
                } else {
                    
                    let urlPicture = savedUser.docs[i].localHref
                    let response = await axios.get(`${URL_IMG}${urlPicture}`, {
                        responseType: 'blob'
                    })
                    
                    function readAsDataURL(data) {
                        return new Promise((resolve, reject) => {
                            const reader = new FileReader()
                            reader.readAsDataURL(data)
                            reader.onloadend = () => {
                                resolve(reader.result)
                            }
                        })
                    }

                    const base64Data = await readAsDataURL(response.data)

                    readedPictures.push({
                        idKycDoc: savedUser.docs[i].idKycDoc,
                        name: 'selfie.jpeg',
                        type: savedUser.docs[i].type,
                        url: `data:image/jpeg;base64,${base64Data.slice(21)}`
                    })
                }
            }
        }

        setDefaultSelfiePictures(readedPictures)
        
    }
    
}

我得到了这个:

enter image description here

我可以看到钩子有内容,但该内容直到组件的下一次呈现才会更新,如果我在检测到 .length 已更改时尝试进行任何更改,它会告诉我它是0... 在下一次渲染之后,我得到了这个:

enter image description here

0 个答案:

没有答案