首页 > 解决方案 > React.JS:以编程方式创建表头的问题

问题描述

我对 React 很陌生,并且在以编程方式呈现表的标题时遇到问题:基本上我希望每个标题都来自一个数组。我在构造函数中创建数组,稍后引用它。现在我只想获取工作人员的标题,但稍后我想为每个单元格设置一个数组中的值。我到目前为止是这样的:

import React from "react";
import firebase from "../firestore";

const db = firebase.firestore();
const docRef = db.collection("tournaments").doc("Siege");


class Table extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
              matches: [],
              headers:[],
        };
    }

    componentDidMount() {
        let headers =["Time"];
        let matches = docRef.collection("Matches").get().then(querySnapshot => {
            matches = querySnapshot.docs.map(doc => doc.data());
            this.setState( {matches});
            docRef.get().then(snapshot=> {
                var noPitches=snapshot.data().numberPitches;
                for (let i=1; i<noPitches; i++){
                    headers.push("Pitch " + i);
                }
            });
            this.setState({headers});
        });
    }





    render() {

        return (

            <div>
                <table id='mytable'>
                    <thead>
                    <tr>
                        { this.state.headers.map((header,index) =>
                        <th key={index}>{header} </th>
                        )}
                    </tr>
                    </thead>
                </table>
            </div>
        )
    }
}
export default Table;


当表格被渲染时,我只能看到第一个标题,时间。将标题数组输出到控制台时,我可以看到,它实际上执行了 3 次日志。前两次,headers 和 this.state.headers 都是空的,第三次它记录了正确的值。我对正在发生的事情感到非常困惑,任何帮助将不胜感激。

网页控制台 表输出

标签: javascripthtmlreactjsgoogle-cloud-firestore

解决方案


推荐阅读