【发布时间】:2021-08-01 01:56:01
【问题描述】:
最初,我只获得了每个键的值,但现在我意识到我将需要这些键本身,然后获取这些键的值。我注释掉了我之前所做的。
// READ LIST OF STORIES (myFirebase.js)
getListOfStories(location, callWhenFinished) {
let ref = firebase.database().ref(location)
ref
.once("value")
.then((snapshot) => {
let listOfStoryKeys = [];
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key
listOfStoryKeys.push(key);
})
for (var storyKey in listOfStoryKeys) {
// printing each story key
console.log(listOfStoryKeys[storyKey])
}
callWhenFinished(listOfStoryKeys);
// var listOfStories = snapshot.val() || [] // all stories or none at all
// callWhenFinished(Object.values(listOfStories));
})
.catch((error) => {
console.log("Couldn't get list of objects: " + error);
callWhenFinished([])
});
}
// OTHERPAGE.js Show stories and their values from the DB and into the console
displayStoriesOnPage = (stories) => {
if (stories.length === 0) {
console.log("Error: Did not get list of stories!");
return;
}
// Initially got all the values of each story;
// Now need to get values of each story using their keys
/*
console.log(stories);
for (var iStory in stories) {
const story = stories[iStory]
console.log("Story: " + story);
for (var iAttr in story) {
const attr = story[iAttr];
console.log("\t " + iAttr + ": " + attr);
}
}
*/
this.setState((state) => {
return {
...state,
allStories: stories,
};
})
}
【问题讨论】:
-
你能解释一下吗?你对这个故事有什么看法,你想得到什么?
-
@Dharmaraj 我想使用每个键获取值(实际数据)。例如,键“-MftXA1QzVOMnf4qbako”应该给我它的所有数据或子项(imgID、语言、位置、状态、标题、用户ID)。我最初只是轻松地获取每组数据,但我现在正在努力通过其唯一键获取一组数据
-
当您获取数据时,除了键之外,您不存储任何内容。现在,您可以通过将 ref 设置为
.ref("stories/"+theKey)向 Firebase 发出另一个请求以获取密钥数据,但这是多余的。关注@Frank 的详细回答。
标签: reactjs firebase firebase-realtime-database