无法显示从Firebase提取的数据到reactjs Webapp

时间:2020-05-25 12:52:47

标签: javascript arrays reactjs firebase firebase-realtime-database

import React, { Component } from 'react'
import * as ReactBootStrap from 'react-bootstrap'
import { Table } from 'react-bootstrap'
import firebase from '../fire'
import '../App.css'
import Foot from './Foot'


class Appointment extends Component {

  state = {
    data: []
  }
  componentDidMount() {
    firebase.database().ref("appoinment").once("value").then(snapShot => {
      snapShot.forEach(item => {

        this.state.data.push({
          id: item.key,
          name: item.val().name,
          age: item.val().age,
          gender: item.val().gender,
          Description: item.val().Description,
          date: item.val().Appointdate
        });

      })
    })
  }

  render() {
    return (
      <div className='cardback'>
        <div>
          <br></br>
          {console.log(this.state)}

          <br></br>
          <h2 style={{ textAlign: 'center', fontSize: '30px' }}>Today's Appointment</h2>
          <br></br>
          <br></br>
          <Table striped bordered hover variant="dark" style={{ width: "1200px", margin: 'auto' }}>
            <thead>
              <tr>
                <td>id</td>
                <td>name</td>
                <td>age</td>
                <td>gender</td>
                <td>Description</td>
                <td>date</td>
                <td>Status</td>
              </tr>
            </thead>
            <tbody>

              **{
                this.state.data.map((item) =>
                  <tr>
                    <td>{item.id}</td>
                    <td>{item.name}</td>
                    <td>{item.age}</td>
                    <td>{item.gender}</td>
                    <td>{item.Description}</td>
                    <td></td>
                  </tr>
                )
              }**
                        </tbody>
          </Table>
          <br></br>
          <br></br>


        </div>
        <Foot></Foot>

      </div>

    )
  }
}
export default Appointment;

这是上面的代码

我想从Firebase提取数据以进行react-js应用程序。我能够在控制台上获取全部数据,但无法将其迭代成表格形式。如下。在其中,我从firebase提取数据并将其推送到数组数据中。因此,基本上数据是对象数组。但是我无法迭代我

1 个答案:

答案 0 :(得分:0)

您正在直接更改状态,不会导致任何重新渲染。不要做this.state.data.push({id:item.key,

使用this.setState

componentDidMount() {
  firebase
    .database()
    .ref("appoinment")
    .once("value")
    .then((snapShot) => {
      let updatedData = [];
      snapShot.forEach((item) => {
        updatedData.push({
          id: item.key,
          name: item.val().name,
          age: item.val().age,
          gender: item.val().gender,
          Description: item.val().Description,
          date: item.val().Appointdate,
        });
      });
      this.setState({ data: updatedData });
    });
}