在React Native中从Fire读取特定值

时间:2019-03-15 11:57:52

标签: react-native react-navigation

尝试执行类似SELECT的查询来检索数据,但使用Firebase和React Native。

我的Firebase数据库中具有以下结构:

{
  "items" : {
    "1234" : {
      "value1" : 420,
      "value2" : 69,
      "ProductID" : 1234
    },
    "5678" : {
      "value1" : 250,
      "value2" : 12,
      "ProductID" : 5678
    },
    "91011" : {
      "value1" : 9001,
      "value2" : 5,
      "ProductID" : 91011
    }
  }
}

我正在使用以下代码尝试检索特定的产品ID

firebaseDB.ref("/items/")
    .orderByChild("ProductID")
    .equalTo(data)
    .once("value", snapshot => {
        if (snapshot.exists()){
            const userData = snapshot.val();
            console.log("INFO ::: Exists!", userData);
        }
        else {
            console.log("INFO ::: No match!!!");
        }

现在我的问题是我似乎无法选择数据。我认为这是我查询的问题,因为我传递了ID 1234,但找不到此产品ID。

        .equalTo(data) <---- is how I'm passing the product id

这是我的日志中打印的内容:

[11:43:19] [FIREBASE] p:0: Listen called for /items{"ep":"1234","i":"ProductID","sp":"1234"}
[11:43:19] [FIREBASE] p:0: Listen on /itemsfor {"ep":"1234","i":"ProductID","sp":"1234"}
[11:43:19] [FIREBASE] p:0: {"r":2,"a":"q","b":{"p":"/items","q":{"sp":"1234","ep":"1234","i":"ProductID"},"t":1,"h":""}}
[11:43:19] [FIREBASE] p:0: handleServerMessage d {"p":"items","d":{"1234":{"value1":420,"value2":69,"ProductID":1234},"5678":{"value1":250,"value2":12,"ProductID":5678},"91011":{"value1":9001,"value2":5,"ProductID":91011}}}
[11:43:19] [FIREBASE] event: /items:value:null
[11:43:19] [FIREBASE] p:0: Unlisten called for /items {"ep":"1234","i":"ProductID","sp":"1234"}
[11:43:19] [FIREBASE] p:0: Unlisten on /items for {"ep":"1234","i":"ProductID","sp":"1234"}

也许我应该尝试修改在调用.once时传递的“值”,但是我不确定...。

谢谢

已解决的问题:

穆罕默德(Mohammed)很好地提出了一个解决方案,该解决方案确实允许检索数据。我也忽略了我正在使用String查询数据,而我正在寻找的数据是一个数字。

1 个答案:

答案 0 :(得分:0)

您可以尝试

const data = 1234;
firebase
  .database()
  .ref()
  .child('items')
  .orderByChild('ProductID')
  .equalTo(data)
  .once('value')
  .then(snapShot => {
    let matchingProducts = [];
    snapShot.forEach(child => {
      matchingProducts = [child.val(), ...matchingProducts];
    });
    console.log("matchingProducts",matchingProducts);
    return matchingProducts;
  });