从Firebase成功删除项目后出现错误

时间:2019-07-06 21:42:54

标签: reactjs firebase-realtime-database

我尝试从创建的Firebase中删除一个项目。实际上,它已从数据库中将其删除,但页面显示了错误:

  

TypeError:无法读取null的属性“ -Lj884cBwoz7QsEyBxTK”

screenshot of the error

这是我的代码

//retrieve data from database and store it in state

fetch(e){

const index = e.target.id;

      this.database.on('value', (e)=>{

let student = e.val()[index]
const student_name = student.full_name;
const age = student.age
const gender = student.gender
const email = student.email
const admission_year = student.admission_year
const country = student.country

          this.setState({
            student_id : index,
            current_student: student_name,
              current_student_age: age,
              current_student_gender: gender,
              current_student_admission_year: admission_year,
              current_student_email: email,
              current_student_country: country,
            })


  })
}


//remove student
removeStudent(){

  return firebase.database().ref('studentsInfo').child(this.state.student_id).remove()

  }

并将removeStudent函数简单地链接到这样的按钮

<button onClick={this.removeIt} className='delete'>Delete Student</button>

该错误提到问题出在提取函数中。 我后来用它从数据库中检索学生的信息,并且运行良好。

removeStudent函数仍将学生从数据库中删除,但是会产生与访存函数有关的错误。

我希望我能很好地解释我的问题。

2 个答案:

答案 0 :(得分:0)

删除记录后,数据快照为空。在您的值更改处理程序中,e.val()将返回null。已删除的数据不再可用。

首先检查快照是否为空,并采取适当的措施:

this.database.on('value', (e) => {
    if (e.val() === null) {
        this.setState({
            // State after deleting the record
        });
    }

    return;
}

答案 1 :(得分:0)

您的fetch方法的读取方式与仅检索一次数据的方式相同。但是您要在其中附加一个on()侦听器,该侦听器在fetch()完成后将保持活动状态。因此,当您删除节点时,on()回调会再次触发,并且此时let student = e.val()[index]可能不再正确,因为index具有您先前确定的值。

如果您只想检索一次数据,请改用once()方法:

fetch(e){

    const index = e.target.id;

    this.database.once('value', (e)=>{
        let student = e.val()[index]
        ...
相关问题