Firebase数据库抛出“错误:Reference.set失败”

时间:2018-07-27 14:30:56

标签: reactjs firebase firebase-realtime-database

我正在尝试将一组数据推送到我的Firebase数据库,但始终返回错误。一直在尝试不同的修复程序,但没有一个起作用。

这是错误页面的图片:1

Error: Reference.set failed: First argument contains undefined in property 'opportunities.-LIR7YgffdqEs86nggb6.opportunityTitle'

如果有人可以帮助我,将永远感激不尽:)

代码:

class App extends Component {
  constructor(props){
    super(props);
    this.addOpportunity = this.addOpportunity.bind(this);
    this.removeOpportunity = this.removeOpportunity.bind(this);

    this.app = firebase.initializeApp(DB_CONFIG);
    this.database = this.app.database().ref().child('opportunities');

    //We are going to setup the React state of our component
    this.state = {
      opportunities: [],
    }
  }

  componentWillMount(){
    const previousOpportunities = this.state.opportunities;

    // Data Snapshot
    this.database.on('child_added', snap => {
      previousOpportunities.push({
        id: snap.key,
        opportunityTitle: snap.val(),
        opportunityCompany: snap.val().opportunityCompany,
        opportunityLocation: snap.val().opportunityLocation,
        opportunityDescription: snap.val().opportunityDescription,
        opportunityLink: snap.val().opportunityLink,
      })

      this.setState({
        opportunities: previousOpportunities
      })
    })

    this.database.on('child_removed', snap => {
      for(var i=0; i < previousOpportunities.length; i++){
        if(previousOpportunities[i].id === snap.key){
          previousOpportunities.splice(i, 1);
      }
    }

    this.setState({
      opportunities: previousOpportunities
    })
  })
}

  addOpportunity(){
    this.database.push().set({opportunityTitle: this.state.newopportunityTitle,
                              opportunityCompany: this.state.newopportunityCompany,
                              opportunityLocation: this.state.newopportunityLocation,
                              opportunityDescription: this.state.newopportunityDescription,
                              opportunityLink: this.state.newopportunityLink});
  }

2 个答案:

答案 0 :(得分:0)

我认为您希望使用this.state.opportunityTitle而不是this.state.newopportunityTitle

答案 1 :(得分:0)

非常感谢Colin!当我执行以下操作时,它似乎正在工作:

addOpportunity(newOpportunityTitle, newopportunityCompany, 
newopportunityLocation, newopportunityDescription, newopportunityLink){

this.database.push({opportunityTitle: newOpportunityTitle,
                    opportunityCompany: newopportunityCompany,
                    opportunityLocation: newopportunityLocation,
                    opportunityDescription: newopportunityDescription,
                    opportunityLink: newopportunityLink});

}