如何从Firebase React获取并显示所有子列表

时间:2017-07-09 23:13:30

标签: javascript reactjs firebase web-applications firebase-realtime-database

我正在尝试通过获取用户帖子来执行类似“博客帖子”的操作,将其推送到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数据库

enter image description here

获得此结果

enter image description here

那么我应该如何显示结果模式等元素并显示所有数据列表。

1 个答案:

答案 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>

the result. enter image description here

相关问题