【问题标题】:how to bind 'this' inside a function in react? [duplicate]如何在反应中将“this”绑定到函数中? [复制]
【发布时间】:2018-07-13 19:09:15
【问题描述】:

这是我用来检查一个人是否已经投票的功能。我正在使用 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”在“this.props.history.push('/thanks')”行中为空。
我知道我需要绑定这个。但是我该怎么做呢?

【问题讨论】:

    标签: reactjs firebase react-native this bind


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      相关资源
      最近更新 更多