避免使用useEffect

时间:2020-07-08 16:17:04

标签: reactjs firebase react-hooks use-effect

问题:我有一个useEffect,在这里我从4个不同的Firebase集合中收集数据。这会使站点(重新)渲染4次。问题是如何避免这种情况?我知道它对于每个setState都是正确的,但是不确定如何避免这种情况。我假设我将不得不使用某种异步功能?

我对异步函数还很陌生,我想也许可以使用promise->对每个onSnap函数进行解析,但这不会破坏侦听器的分离吗?

以下代码:

 useEffect(() => {

        const unsubInstruments = DB.collection(`organizations/${window.localStorage.getItem(OrgKey)}/assets/instrumentarchive/items`)
        const unsubUniforms = DB.collection(`organizations/${window.localStorage.getItem(OrgKey)}/assets/uniformarchive/items`)
        const unsubOtherAssets = DB.collection(`organizations/${window.localStorage.getItem(OrgKey)}/assets/other_assets/items`)

        const unsubAssetsCollection = DB.collection(`organizations/${window.localStorage.getItem(OrgKey)}/assets`)

        const getCollectionSizes = async () => {

            const assetsSize = () => {
                unsubAssetsCollection.onSnapshot((snap) => {
                    let assetsSize = snap.size
                    setAssetsSize(assetsSize)
                })
                return () => unsubInstruments()
            }

            const instrumentsSize = () => {
                unsubInstruments.onSnapshot((snap) => {
                    let instruments = snap.size
                    setInstruments(instruments)
                })
                return () => unsubInstruments()
            }

            const uniformsSize = () => {
                unsubUniforms.onSnapshot((snap) => {
                    let uniforms = snap.size
                    setUniforms(uniforms)
                })
                return () => unsubUniforms()
            }

            const otherAssetsSize = () => {
                unsubOtherAssets.onSnapshot((snap) => {
                    let otherAssets = snap.size
                    setOtherAssets(otherAssets)
                })
                return () => unsubOtherAssets()
            }

            assetsSize()
            instrumentsSize()
            uniformsSize()
            otherAssetsSize()

        }

        getCollectionSizes()
    }, [])

1 个答案:

答案 0 :(得分:0)

因此,正如评论所说,答案是不要像我一样使用状态,而要使用一个状态,其中包含状态变量。