如何绑定这个'在一个函数里面做出反应?

时间:2018-02-03 11:43:45

标签: reactjs firebase react-native this bind

这是我用来检查一个人是否已投票的功能。我正在使用firebase后端。

madeVote() {
  let id = this.state.id
  var userid = this.props.location.state.userid;

  var idRef = database.ref('/voted/' + userid);
  if (id == -1) {
    alert("Please select a candidate")
  } else {

    var idQuery = idRef.child('voted');
    //console.log(userid);
    idQuery.once("value", function(snapshot) {
      console.log("Value " + snapshot.val());
      if (1) {
        alert("You have already voted")
        this.props.history.push('/thanks')
      }
    })
  }
}

'这'在行中为空" this.props.history.push(' / thanks')"。
我明白我需要绑定它。但是我怎么做到这里呢?。

1 个答案:

答案 0 :(得分:3)

只需使用箭头功能。它会自动将this绑定到您的功能

idQuery.once("value", (snapshot)=> {
      console.log("Value " + snapshot.val());
      if (1) {
        alert("You have already voted")
        this.props.history.push('/thanks')
      }
    })
相关问题