从Firebase查询更新变量的值? [英] Update value of variable from Firebase query?

查看:129
本文介绍了从Firebase查询更新变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在试图从中使用取一个项目的值,一次,并使用这个值来填充var itemsList 。但是,尽管itemsList在中正确地填充了一次调用,但它在调用之外记录为undefined。我认为这可能与Firebase的异步本质有关,但我不确定如何解决此问题。有什么建议么?

  submitAnswer:function(){
var userRef = usersRef.child(key);

//获取用户
的items_list var itemsList;
userRef.once('value',(snap)=> {
itemsList = snap.val()。items_list;
console.log('items list populated here'+ itemsList) ;
});

console.log(items list not populated here+ itemsList);
},


解决方案

Firebase调用,它是异步的,在记录未填充的itemsList之前代码不会等待它完成。如果你只是想用数据做一些简单的事情,在执行任何操作之前一定要检查它是否存在(并且像你一样处理它)任何异步数据)。

  if(itemsList){
console.log('My items have arrived!'+ itemsList);





$ b如果这些数据将会被传播到你的应用程序中,使用来自Firebase的响应数据调用setState()以触发您刚刚获取的新数据的组件重新呈现。



所以,我们可以这样做:

  userRef.once value,(snap)=> {
itemsList = snap.val()。items_list;

this.setState({
items:itemsList;
});

} .bind(this));


I currently am trying to pull the value of an item from a firebase using once, and use this value to populate the var itemsList. However, although itemsList is correctly populated within the once call, it is logging as undefined outside the call. I think this may have something to do with the asynchronous nature of Firebase, but I'm not sure how to remedy this problem. Any suggestions?

submitAnswer: function() {
    var userRef = usersRef.child(key);

    //get items_list for user
    var itemsList;
    userRef.once('value', (snap) => {
        itemsList = snap.val().items_list;
        console.log('items list populated here' + itemsList);
    });

    console.log("items list not populated here" + itemsList);
},

解决方案

You're correct about the Firebase call, it's asynchronous and the code isn't going to wait for it to complete before logging the unpopulated itemsList.

If you're only looking to do something simple with the data, just be sure to check that it exists before performing any action with it (and handle it like you would any async data).

if(itemsList){
  console.log('My items have arrived! ' + itemsList);
}

If that data is going to be propagated further down your app it is usually suggested to make a call to setState() with your response data from Firebase to trigger a re-render of your components with the new data you just fetched.

So something along the lines of:

userRef.once("value", (snap) => {
  itemsList = snap.val().items_list;

  this.setState({
    items: itemsList;
  });

}.bind(this));

这篇关于从Firebase查询更新变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆