在componentDidMount中,第一个console.log(this)给了我正确的响应(" ThumbNail {props:Object,context:Object,refs:Object,updater:Object,state:Object ...}&#34 ;)
但是当在firebase查询中使用时(即orderbyChild),它的console.log(this)返回null。我正在尝试使用函数" this.handleArticle"在查询中但我一直收到此错误"无法读取属性' _handleArticle' of null"。
componentDidMount() {
//adds the change listener to listen to changes in TeamStore
TeamStore.addChangeListener(this._onChange);
// triggers updateArticle
// bind article to current state.name
this._updateArticle();
console.log(this); //this one is right
//get new article as notification
var teamResRef = new Firebase(this.props.baseUrl + this.state.name + '/results');
teamResRef.orderByChild('timeStamp').startAt(Date.now()).on('child_added', function(snapshot) {
var newArticle = snapshot.val();
// console.log(newArticle);
// _handleArticle(newArticle);
console.log(this); //this one returns null
});
}
答案 0 :(得分:3)
您需要将this
设置为回调函数(因为在回调this
中未引用React
组件Object
),为此,您可以使用{{3}像这样的方法
teamResRef
.orderByChild('timeStamp')
.startAt(Date.now())
.on('child_added', function(snapshot) {
// code
}.bind(this));
如上所述 @David East ,您也可以通过.bind
中的第四个参数设置this
,就像这样
teamResRef
.orderByChild('timeStamp')
.startAt(Date.now())
.on('child_added', function(snapshot) {
// code
}, null, this);