【问题标题】:"this" is null in firebase query function in reactjsreactjs的firebase查询函数中的“this”为空
【发布时间】:2016-04-07 06:07:09
【问题描述】:

在componentDidMount中,第一个console.log(this)给了我正确的响应("ThumbNail {props: Object, context: Object, refs: Object, updater: Object, state: Object...}")

但在 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
        });
    }

【问题讨论】:

    标签: reactjs firebase


    【解决方案1】:

    你需要将this设置为回调函数(因为在回调中this没有引用React组件Object),你可以使用.bind这样的方法

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

    @David East所说,你也可以通过.on中的第四个参数设置this,像这样

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

    【讨论】:

    • Firebase 回调中的上下文 this 与 React 组件中的上下文不同。您还可以将上下文设置为.on() 函数中的第四个参数。
    猜你喜欢
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 2020-09-25
    • 2017-09-19
    • 2018-10-16
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    相关资源
    最近更新 更多