这里的目的是拥有一组频道 ID,我可以在其中使用来自我的 Firebase 的信息填充他。
我有这样的组件:
export default function Component() {
const [channelsId, setChannelsId] = useState([])
// and I call this function passing my state
useEffect(() => {
getChannelsIds(someId, channelsId, setChannelsId)
}, [])
功能:
export const getChannelsIds = (someId, channelsId, setChannelsId) => {
try {
firestore.collection("channels").where("someId", "==", someId).get().then(querySnapshot => {
querySnapshot.forEach(doc => {
setChannelsId([...channelsId, doc.data().id])
})
})
} catch (err) {
toast.error('Error while trying to get the channel.')
}
}
它不起作用,因为我的 channelsId 状态被覆盖,我只有最后一个 channelId,console.log 屏幕截图:
您应该使用功能更新
export const getChannelsIds = (someId, channelsId, setChannelsId) => {
try {
firestore.collection("channels").where("someId", "==", someId).get().then(querySnapshot => {
querySnapshot.forEach(doc => {
setChannelsId(ids => [...ids, doc.data().id]);
})
})
} catch (err) {
toast.error('Error while trying to get the channel.')
}
}
或者更好的是,您可以首先使用新数据创建一个数组,并且只更新一次状态。
export const getChannelsIds = (someId, channelsId, setChannelsId) => {
try {
firestore.collection("channels").where("someId", "==", someId).get().then(querySnapshot => {
const newChannelIds = querySnapshot.map(doc => doc.data().id);
setChannelsId([...channelsId, ...newChannelIds);
});
}
catch (err) {
toast.error('Error while trying to get the channel.')
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句