【问题标题】:Avoid rerender on several firebase snapshots with useEffect使用 useEffect 避免在多个 firebase 快照上重新渲染
【发布时间】:2020-10-29 02:50:59
【问题描述】:

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

我对异步函数很陌生,我想也许可以在每个 onSnap 函数上使用 promise -> resolve,但这不会破坏监听器分离吗?

代码如下:

 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()
    }, [])

【问题讨论】:

  • 您将数据设置为组件的不同状态,不是吗?我的意思是调用setUniformssetInstruments 等函数。
  • 所以我宁愿有这样一个状态:const [state, setState] = usestate({ instruments : "", uniforms : "" }) 然后把数据设置成这个?
  • 是的,你是对的。如果您只有一个状态,则将调用一次重新渲染。

标签: reactjs firebase react-hooks use-effect


【解决方案1】:

所以正如 cmets 所说,答案是不要像我所做的那样使用状态,而是拥有一个状态,其中包含状态变量。

【讨论】:

    猜你喜欢
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2021-08-04
    • 2020-04-23
    • 2020-08-14
    • 1970-01-01
    相关资源
    最近更新 更多