如何从Firebase React获取并显示所有子列表 [英] How to get and display all child list from Firebase React
本文介绍了如何从Firebase React获取并显示所有子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过获取用户帖子,将其推送到firebase上,然后再将其返回以显示在element上来执行类似博客文章"的操作.这是我的代码的一部分
I'm trying to do something like "blog post" by getting user post, push it onto firebase and then get it back to display on element. Here is a part of my code
constructor(props){
super(props);
this.state = {
title: '',
story: '',
date: ''
};
}
componentDidMount(){
const rootRef = firebase.database().ref();
const post = rootRef.child('post').orderByKey();
post.once('value', snap => {
snap.forEach(child => {
this.setState({
date: child.key,
title: child.val().title,
story: child.val().story
})
});
});
}
在render()
<div className="post">
<h3>{this.state.date}</h3>
<h2>{this.state.title}</h2>
<p>{this.state.story}</p>
</div>
在Firebase数据库上
on firebase database
获得此结果
所以我应该如何显示类似于结果模式的元素并可以显示所有数据列表.
推荐答案
我这样做是得到正确的结果
I get the correct result by doing like this
constructor(props){
super(props);
this.state = {
title: [],
story: [],
date: [],
post: '',
};
};}
componentDidMount(){
const rootRef = firebase.database().ref();
const post = rootRef.child('post').orderByKey();
post.once('value', snap => {
snap.forEach(child => {
this.setState({
date: this.state.date.concat([child.key]),
title: this.state.title.concat([child.val().title]),
story: this.state.story.concat([child.val().story])
});
const postList = this.state.date.map((dataList, index) =>
<p>
{dataList}
<br />
{this.state.title[index]}
<br />
{this.state.story[index]}
<hr />
</p>
);
this.setState({
post: postList
});
});
}); }
在render()
<div className="diary">
<ul>{this.state.post}</ul>
</div>
结果.
这篇关于如何从Firebase React获取并显示所有子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文