首页 > 解决方案 > 在 react Native 中从 firebase 中选择特定字段(子字段?)

问题描述

这是我的火力基地:

"Locations" : {
   "location01" : {
     "image" : 
     "https://www.senecacollege.ca/content/dam/projects/seneca/homepage-assets/homepage_intl.jpg",
     "instructorName" : " OSMAN H.",
     "place" : "Seneca, Scarborough",
     "timing" : "TBA"
  },
  "location02" : {
     "image" : "https://media-exp1.licdn.com/dms/image/C561BAQHrVTRjljcYnw/company-background_10000/0?e=2159024400&v=beta&t=fp0LWqyEnnXvxjzzdfuCHhX2jflJyhAkS0lMLXsPFw0",
     "instructorName" : "AIYAZ NOOR",
     "place" : "UTSC, Scarborough",
     "timing" : "4 PM - 6 PM"
  }
},

我知道如果我得到这样的数据,那么我可以选择/过滤我想要的特定字段。

let locationsRef = db.ref('/Locations');

  locationsRef.once('value', snapshot => {
      let data = snapshot.val()
      let locationsList = Object.values(data)
      console.log(locationsList);
  })

不幸的是,这会将所有数据作为数组提供并显示每个对象。如果 /locations 分支有很多记录,它会占用空间,我认为这不是最佳实践。有没有办法只选择“地点”字段。键'location01'和'location02'可以是任何东西。所以我不能做像(location/location01)这样的事情,这会带我进入特定的分支。我想从所有分支机构中获取“地点”字段。

我研究了很多,没有运气。非常感谢任何想法/帮助!先感谢您

标签: javascriptreactjsfirebasereact-native

解决方案


我认为您正在寻找的是.mapJavaScript 中的函数。

您可以像这样映射您的位置对象:

const locationsRef = db.ref('/Locations');

locationsRef.once('value', snapshot => {
  let data = snapshot.val()
  let locationsList = Object.values(data)
  locationsList.map((location, index) => {
    console.log(location.place);
    // here you can do whatever you want with every single location object
    // for example return a View that displays only the place
    return <View><Text>{location.place}</Text></View>
  });
});

您可以在此处.map阅读MDN 文档中有关该功能的更多信息。

PS我改变了你的使用,let以防const你的数据库数据是一个你在这个特定视图中没有改变的常量。


推荐阅读