&引用;这";在reactjs中的firebase查询函数中为null

&引用;这";在reactjs中的firebase查询函数中为null,reactjs,firebase,Reactjs,Firebase,在componentDidMount中,第一个console.log(this)给了我正确的响应(“缩略图{props:Object,context:Object,refs:Object,updater:Object,state:Object…}”) 但在firebase查询(即orderbyChild)中使用时,其console.log(this)返回null。我试图在查询中使用函数“this.handleArticle”,但我一直遇到这样的错误“无法读取null的属性'\u handleAr

在componentDidMount中,第一个console.log(this)给了我正确的响应(“缩略图{props:Object,context:Object,refs:Object,updater:Object,state:Object…}”)

但在firebase查询(即orderbyChild)中使用时,其console.log(this)返回null。我试图在查询中使用函数“this.handleArticle”,但我一直遇到这样的错误“无法读取null的属性'\u handleArticle'


您需要将
this
设置为回调函数(因为在回调
中,this
不引用
React
组件
对象
),要做到这一点,您可以使用如下方法

teamResRef
  .orderByChild('timeStamp')
  .startAt(Date.now())
  .on('child_added', function(snapshot) {
     // code
  }.bind(this));
teamResRef
  .orderByChild('timeStamp')
  .startAt(Date.now())
  .on('child_added', function(snapshot) {
      // code
   }, null, this);
如前所述,@David East,您也可以通过中的第四个参数设置
,如下所示

teamResRef
  .orderByChild('timeStamp')
  .startAt(Date.now())
  .on('child_added', function(snapshot) {
     // code
  }.bind(this));
teamResRef
  .orderByChild('timeStamp')
  .startAt(Date.now())
  .on('child_added', function(snapshot) {
      // code
   }, null, this);

Firebase回调中的上下文
与React组件中的上下文
不同。您还可以将上下文设置为
.on()
函数中的第四个参数。