【发布时间】:2016-09-13 13:27:07
【问题描述】:
我遇到了一个奇怪的问题,一旦我将一个值推送到 Firebase 对象,就会发生两件事:
- 当我从 Firebase 拉取对象时,我无法在收到的数组中访问它。
- 我收到的数组没有
length属性。
这是我的 Firebase 结构的样子:
"user_solutions": {
"0":
{
"user_id": 0,
"clue_id": 0,
"hunt_id": 0,
"completed": 1
},
"1":
{
"user_id": 0,
"clue_id": 1,
"hunt_id": 0,
"completed": 0
},
"2":
{
"user_id": 0,
"clue_id": 1,
"hunt_id": 1,
"completed": 0
}
},
"-KHxBMZwVMzyiMIcbMdr":
{
clue_id: 1,
completed: 0,
hunt_id: 0,
user_id: 0
}
这是有问题的函数:
userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', (snap) => {
var solution = snap.val();
for (var i = 0; i < solution.length; i++) {
if (solution[i].hunt_id == 0) {
solutionsForThisHunt.push(solution[i]);
}
}
this.populateArray(solutionsForThisHunt);
});
当我运行调试器时,solution 的值为 Object {0: Object, 1: Object, 2: Object, -KHxBMZwVMzyiMIcbMdr: Object},但 length 属性未定义。 solutionsForThisHunt 永远不会被填充。此外,我可以通过snap.val()[0]/snap.val()[1]/snap.val()[2] 在调试器中单独访问对象,但由于某种原因,当我尝试访问snap.val()[3] 时,它是未定义的,尽管它应该被填充。
【问题讨论】:
-
snap.val是返回一个真正的数组还是另一个可迭代的数组?Array.isArray返回什么? (developer.mozilla.org/de/docs/Web/JavaScript/Reference/…) -
你是对的!我的印象是它返回了一个数组,但它只是一个可迭代的。您的解决方案有效,谢谢。
-
Firebase 不会在此处返回数组,因为看起来您将密钥存储为字符串。 Storing them as integers would make a difference,虽然我总是建议不要depend on array semantics when it comes to Firebase。
标签: javascript arrays reactjs firebase react-native