【发布时间】: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()
}, [])
【问题讨论】:
-
您将数据设置为组件的不同状态,不是吗?我的意思是调用
setUniforms、setInstruments等函数。 -
所以我宁愿有这样一个状态:
const [state, setState] = usestate({ instruments : "", uniforms : "" })然后把数据设置成这个? -
是的,你是对的。如果您只有一个状态,则将调用一次重新渲染。
标签: reactjs firebase react-hooks use-effect