【问题标题】:Firebase values are properly pulled but cannot be accessed?Firebase 值已正确提取但无法访问?
【发布时间】:2016-09-13 13:27:07
【问题描述】:

我遇到了一个奇怪的问题,一旦我将一个值推送到 Firebase 对象,就会发生两件事:

  1. 当我从 Firebase 拉取对象时,我无法在收到的数组中访问它。
  2. 我收到的数组没有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] 时,它是未定义的,尽管它应该被填充。

【问题讨论】:

标签: javascript arrays reactjs firebase react-native


【解决方案1】:

解决方案似乎是一个带有键的对象,而不是一个数组。您可以执行以下操作

var solution = snap.val(); 
var array = Object.keys(solution).map(key => ({ ...solution[key], id: key }));
for ....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多