![](/img/trans.png)
[英]How to check Item exists in Firebase Database? - react-native-firebase
[英]React-native-firebase Database - Retrieve datas from nested calls
我有這樣的Firebase數據庫(例如):
{
'itemCategories': [
_categoryKey1: {
name: 'Category 1'
},
_categoryKey2: {
name: 'Category 2'
},
_categoryKey3: {
name: 'Category 3'
},
],
'items': [
_itemKey1: {
categoryId: '_categoryKey1',
name: 'Item 1',
}
_itemKey2: {
categoryId: '_categoryKey2',
name: 'Item 2',
}
_itemKey3: {
categoryId: '_categoryKey1',
name: 'Item 3',
}
_itemKey4: {
categoryId: '_categoryKey3',
name: 'Item 4',
}
_itemKey5: {
categoryId: '_categoryKey3',
name: 'Item 5',
}
]
}
我想要得到的是一組按類別分組的項目,例如:
itemList = [
{
category: 'Category 1',
items: [
{
id: '_itemKey1',
categoryId: '_categoryKey1',
name: 'Item 1',
},
{
id: '_itemKey3',
categoryId: '_categoryKey1',
name: 'Item 3',
}
]
},
{
category: 'Category 2',
items: [
{
id: '_itemKey2',
categoryId: '_categoryKey2',
name: 'Item 2',
}
]
},
{
category: 'Category 3',
items: [
{
id: '_itemKey4',
categoryId: '_categoryKey3',
name: 'Item 4',
},
{
id: '_itemKey5',
categoryId: '_categoryKey3',
name: 'Item 5',
},
]
},
]
我使用react-redux
動作來實現這一點,就像這樣:
export const setItemList = (list) => {
return {
type: 'setItemList',
value: list
}
}
export const getItemListByCategory = () => {
return (dispatch) => {
let itemList = []
firebase.database().ref('itemCategories').on('value', (snapCategory) => {
snapCategory.forEach((category) => {
const categoryId = category.key
firebase.database().ref('items').orderByChild('categoryId').equalTo(categoryId).on('value', (snapItem) => {
let items = []
snapItem.forEach((item) => {
items.push({
id: item.key,
...item.val()
})
})
itemList.push({
category: category.val().name,
items: items
})
// This is where I think is the issue
dispatch(setItemList(itemList))
})
})
// The dispatch should be there, when every calls resolved
})
}
}
在大多數情況下 ,這效果很好。 當我處於forEach
循環中時,我將按類別檢索數據,並實際上分派多個部分 itemList
直到forEach
循環結束。 顯然,我寧願等到循環結束再調度完整的itemList
。
我不知道如何等待循環結束-以及所有要解決的電話。 我覺得我應該與Promise
但是我不確定如何實現它。
如何使用Promise.all()? 除了可以在firebase.database().ref('items').orderByChild('categoryId').equalTo(categoryId).on
中觸發調度外,您還可以將此調用添加到promises數組中。 像這樣:
const promises = [];
snapCategory.foreach(snap => {
promises.push(your calls here, instead of dispatch return the list here)
})
Promise.all(promises).then((...args) => {
// args should contain all lists here, you can manipulate them as you need
// and dispatch afterwards
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.