首页 > 解决方案 > 如何在 reactjs 中显示从 firestore 获取的数据到 boostrap 表?我可以获取但无法以标准方式显示

问题描述

我正在尝试从 firestore 获取数据并使用 reactjs 将其显示到引导表中。我能够获取数据并将其存储在地图中,我什至可以使用开发人员工具进行控制台并查看它。但是,在将其显示到表格时,我使用了正确的方法来循环地图并填充它,但它无法显示任何内容。我需要帮助。

    constructor(){
    super();
       this.state={
         mydata=[]
      }
     }
    getUsers=async()=>{
    console.log("hello");
    await firebaseapp.firestore().collection('users').get()
    .then((snapshot) => {
      //console.log(snapshot);
      snapshot.forEach((doc,key) => {

        mydata.push({username:doc.data().username,group:doc.data().group,email:doc.data().email});

      });
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });


   }



    render(){
         return(
       <Paper className={styles.root}>
       <Table className={styles.table}>
        <TableHead>
          <TableRow>
            <TableCell  className={styles.tableCell}>username</TableCell>
            <TableCell  className={styles.tableCell}>email</TableCell>
           <TableCell  className={styles.tableCell}>group</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
              {mydata.map((data,key)=>{
                 return(
                  <TableRow >
                  <TableCell  className={styles.tableCell}>{data.username}</TableCell>
                  <TableCell  className={styles.tableCell}>{data.group}</TableCell>
                  <TableCell  className={styles.tableCell}>{data.emails}</TableCell>
                  </TableRow>
                 )
              })  
              }

        </TableBody>
      </Table>
    </Paper>

          )
    }
     componentDidMount(){
       this.getUsers();
     }

标签: reactjsecmascript-6google-cloud-firestore

解决方案


你不能使用状态变量,所以当你获取数据时它不能重绘。试试这样。

...
    constructor(){
    super();
       this.state={
         mydata: []
      }
     }
...
      let data = [];
      snapshot.forEach((doc,key) => {
          data.push({username:doc.data().username,group:doc.data().
                  group,email:doc.data().email});
      });
     this.setState({mydata: data});
...
  render() {
    const { mydata } = this.state;
   ...
...

推荐阅读