【问题标题】:Getting value from firebase returns error从 firebase 获取价值返回错误
【发布时间】:2017-12-09 06:45:44
【问题描述】:

问题

使用由 React Native 创建的社交媒体应用程序,我尝试使用快照功能从我的 firebase 服务器获取数据,然后将该值加 1,然后在服务器上更新该值。我这样做的代码是:

    this.setState({
      comments: firebase.database().ref('posts/'+this.state.passKey).once('value', function(snapshot) {snapshot.val().comments}) 
        })

    firebase.database().ref('posts').child(this.state.passKey).update({ 
      comments: this.state.comments+1
        })

当我运行这段代码时,我得到一个错误,说:

Reference.update failed: 
First argument contains NaN in property 'posts.randompostkey.comments'

我的服务器

【问题讨论】:

    标签: javascript firebase react-native firebase-realtime-database


    【解决方案1】:

    解决方案是正确同步访问数据:首先确保所有内容都已加载,然后才更新分数。

    看看这个solution

    【讨论】:

    • 我做对了吗?它仍然说未定义。 this.state.cmets.$loaded().then(function() { firebase.database().ref('posts').child(this.state.passKey).update({ latestComment: 'Comment:' + this .state.commentInput, cmets: parseInt(this.state.cmets)+1 })})
    【解决方案2】:

    您需要使用的是 transaction

    postRef.transaction(function (post) {
                if (post) {
                        post.commentCount++;
                    }    
                }
                return post;
            });
    

    通过这种方式,您可以获取数据、更新值,然后以安全的方式将其发回,确保不会被其他人同时更新

    【讨论】:

      【解决方案3】:

      在我看来,firebase 拒绝存储 NaN 值(和未定义的值),即使我在文档中找不到它。 确保不要将 NaN 值发送到 firebase。

      【讨论】:

        猜你喜欢
        • 2017-11-09
        • 1970-01-01
        • 2019-02-07
        • 1970-01-01
        • 1970-01-01
        • 2014-05-04
        • 1970-01-01
        • 2019-12-25
        • 1970-01-01
        相关资源
        最近更新 更多