【问题标题】:(React native) Can't get data out of the Firebase database method(React native) 无法从 Firebase 数据库方法中获取数据
【发布时间】:2019-03-14 12:06:37
【问题描述】:

我试图从我的数据库中获取数据,在 componentWillMount() 中,它可以正常工作:

  var userData = null
firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) {
        userData = snapshot.val()
        console.log(userData)
      });

但它仅在方法中有效,我尝试将值分配给变量,但即使使用 this.setstate,我也无法将其取出。 我真的迷路了,看起来很简单,但我不知道如何...... 感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    once() 是异步的,并立即返回并带有承诺。当您向其附加 then 回调时,该承诺不会阻止您的代码。在数据库查询完成之前,userData 不会在 promise 的回调中填充,并且您无法保证何时会填充。如果您的代码在最终填充之前尝试访问 userData,它仍将具有其原始 null 值。

    【讨论】:

    • 但是日志正在写入数据,我该怎么做呢?
    • 日志正在写入数据,因为它在内部回调中,当您知道数据可用时。仅在调用回调后使用该值。
    • 这就是我想要做的,但我不知道怎么做
    • 我只需要知道如何将 snapshot.val 存储在我可以在外部使用的变量中
    • 你已经在这样做了。您还尝试在设置之前使用它。您需要学习使用 Promise 进行异步编程。
    【解决方案2】:

    嗯,这里发生的事情是,

    您的 firebase 方法需要一些时间来获取数据,因为这里的一切都是异步的,javascript 不会等到您的 firebase 方法被执行。

    firebase.database().... 的下一行将在此完成之前立即执行。

    因此,您可能需要使用 setState 将数据设置为状态,或者您可以使用类变量而不是局部变量。

    这样做,

    constructor(props){
       super(props);
       this.state={
         data:null //either do this
       }
       this.localData=null; // or this
    }
    
    
    firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) {
            this.setState({data:snapshot.val()});
            this.localData = snapshot.val();
            console.log(this.localData)
    });
    

    【讨论】:

    • 你好,我已经尝试过了,它不起作用我得到:react native 可能未处理的承诺拒绝(id 0)类型错误:this.setState 不是函数
    • 您是否将this 绑定到此代码所在的方法?
    • 我在这里解决了我的问题:stackoverflow.com/questions/55170390/…
    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多