我正在尝试通过获取用户帖子来执行类似“博客帖子”的操作,将其推送到firebase,然后将其恢复到元素上显示。 这是我的代码的一部分
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
})
});
});
}
on render()
<div className="post">
<h3>{this.state.date}</h3>
<h2>{this.state.title}</h2>
<p>{this.state.story}</p>
</div>
on firebase数据库
获得此结果
那么我应该如何显示结果模式等元素并显示所有数据列表。
答案 0 :(得分:3)
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
});
});
}); }
on render()
<div className="diary">
<ul>{this.state.post}</ul>
</div>