javascript - 在 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)这样的事情,这会带我进入特定的分支。我想从所有分支机构中获取“地点”字段。
我研究了很多,没有运气。非常感谢任何想法/帮助!先感谢您
解决方案
我认为您正在寻找的是.map
JavaScript 中的函数。
您可以像这样映射您的位置对象:
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
你的数据库数据是一个你在这个特定视图中没有改变的常量。
推荐阅读
- spring - 使用spring webserver在corda中实现RPC安全管理时出现异常
- c# - LoadPackage 从 .NET 失败,找不到集成服务类
- spring-data-jpa - querydsl 存在重复条件
- java - 使用 Maven hawtio:camel 命令在 hawt.io 中运行示例插件
- html - 如何直接在顶部和底部创建带有伪元素的div?
- java - 如何不抛出一般指定的异常?
- php - 如何计算 php 数组中的出现次数
- android - CheckBox 不是用它的勾画出来的
- phabricator - 设置域名以指向您要安装的主机
- machine-learning - 确定 scikit learn FeatureHasher 的 n_features 值