[英]Array's elements' and length's values are undefined (when getting from Firebase)
我可以從數據庫中獲取數組,但是我無法訪問從數據庫中獲取的數組元素,無論是arr[0]
, arr[1]
... 還是arr.length
這就是為什么從數組到 object 的轉換永遠不會發生在下面的toObject
function 中。 即問題, arr.length
和arr[i]
未定義。
那么,如何才能成功登錄console.log(arr)
呢? 是的,它顯示arr
成功。
//Conversion function
const toObject = (arr) => {
//If hardCodedArr attempted to convert, it is succesfully converted to object
//let hardCodedArr= [
// {"id":1, "isLocked": false, "name": "Cars"},
// {"id":2, "isLocked": true, "name": "Planes"},
// {"id":3, "isLocked": true, "name": "Trains"}
//]
//If array taken from Firebase, arr parameter, attempted to convert, it cannot reach to its sub-elements. i.e. arr[0], arr[1] ...
// Therefore, conversion fails
console.log("arr.length: ", arr.length)
//arr.length: undefined
console.log("arr[0]: ", arr[0])
//arr[0]: undefined
console.log("arr:", arr)
//Displays the array!
//arr: [
// {"id":1, "isLocked": false, "name": "Cars"},
// {"id":2, "isLocked": true, "name": "Planes"},
// {"id":3, "isLocked": true, "name": "Trains"}
//]
//array to object conversion occurs here
let rv = {}
for (let i = 0; i < arr.length; ++i) {
rv[i] = arr[i]
}
}
console.log("rv:", rv)
return rv
}
CategoriesScreen
是頂級組件,所有這些都發生在里面。
const CategoriesScreen = () => {
ReadAndWrite(ReadFirebase, WriteFirebase)
...
...
}
const ReadAndWrite = async (function1, function2) => {
try {
const categoriesList = await function1() //reading array from Firebase
console.log(categoriesList)
let obj = toObject(categoriesList)
function2(obj); //sending to Firebase in which I didn't include details here
} catch (error) {
throw error
}
}
const ReadFirebase= async () => {
let topicsData;
try {
await database()
.ref(`topics/`)
.once('value')
.then(snapshot => {
topicsData = snapshot
})
return topicsData
} catch (error) {
throw error
}
}
這是因為您的 arr 類型是DataSnapshop
。 DataSnapshop 不是數組類型 class 您需要將所有項目轉換或 foreach 到新數組。
const ReadFirebase= async () => {
let topicsData;
try {
await database()
.ref(`topics/`)
.once('value')
.then(snapshot => {
topicsData = snapshot.val()
})
return topicsData
} catch (error) {
throw error
}
或者
const ReadFirebase= async () => {
let topicsData;
try {
await database()
.ref(`topics/`)
.once('value')
.then(snapshot => {
snapshot.forEach(function(childSnapshot) {
//add entity your topicdata
});
})
return topicsData
} catch (error) {
throw error
}
有關更多信息,請訪問 https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference#once https://firebase.google.com/docs/reference/js/v8/firebase.database。數據快照
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.