Firebase快照子值在日志中正确,但未设置为状态变量

时间:2019-03-29 21:53:33

标签: reactjs firebase firebase-realtime-database

我正在尝试从我的Firebase数据库检索数据并将值分配给状态变量。

这是方法:

findStudent = async(e) => {
        e.preventDefault()
        var _studentNumber = this.state.StudentNumber
        var _uid = this.state.uid

        // get reference to database location we want
        const loc = firebase.database().ref('/students/' + _uid + '/' + _studentNumber)
        console.log(loc.toString())
        loc.once('value', snapshot => {
            snapshot.forEach(child => {
                this.setState({ 
                    BlockID: child.val().blockchainKey,
                    CourseCode: child.val().courseCode,
                    CourseName:  child.val().courseName,
                    StudentName: child.val().studentName
                })
            })
        })
    }

以下是状态变量:

state = {
        user: '',
        uid: '',

        StudentName: '',
        StudentNumber: '',
        CourseCode: '',
        CourseName: '',
        BlockID: '',
        studentArray: [],
    }

这是我要显示它们的地方:

<div className="row">
                    <div className="col-sm">
                        {this.state.StudentName}
                    </div>
                    <div className="col-sm">
                        {this.state.StudentNumber}
                    </div>
                    <div className="col-sm">
                        {this.state.CourseCode}
                    </div>
                    <div className="col-sm">
                        {this.state.CourseName}
                    </div>
                    <div className="col-sm">
                        {this.state.BlockID}
                    </div>
                </div>

当我console.log child.val()时,我可以看到正确的值,但是没有将它们设置为状态变量。

0 个答案:

没有答案