问题:我有一个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()
}, [])
正如评论所说,答案是不要像我所做的那样使用state,而是使用一个状态,其中包含状态变量。