如何将数据从snapshot.val()内部提升到组件状态?

时间:2019-02-05 00:00:11

标签: javascript reactjs firebase firebase-realtime-database

我正在使用Firebase身份验证登录按钮,该按钮在Promise中引用了我的Firebase实时数据库。当我尝试提起该数据以更改组件状态时,它变为空。

我尝试了一种更简单的方法,即在firebase引用之外声明一个变量,然后尝试在函数中设置该变量。

我还尝试将“ that”设置为空数组变量,然后将其作为数组访问。

我尝试将this设置为that.state.ign,但是当我尝试访问所需的数据时,该数据将为空

** edit-我还认为这是一个异步问题,因此在尝试在firebase引用之外进行console.log之前,我使用了setTimeout 15000允许经过15秒。

 var that = this;
 firebase.database().ref("users/" + this.state.userid).on("value", function (snapshot) {

      var userIGN = (snapshot.val().ign);

      console.log(userIGN); // WORKS - gives ign from database 

      that.setState({ ign: userIGN }); // WORKS - sets that.state.ign to ign from database 

      console.log(that.state.ign); // WORKS - gives ign from that.state 
    })

    console.log(that); // WORKS - shows object that has state with ign

    console.log(that.state); // FAIL - shows state object, but ign is null now?!

第二个console.log(that.state.ign)应该显示Firebase参考中的数据点

1 个答案:

答案 0 :(得分:-2)

事实证明,即使使用15秒的setTimeout,但由于我的网络服务非常差/不稳定,超时时间还不够长。我尝试了30秒,就可以访问数据!

var that = this;
    firebase.database().ref("users/" + this.state.userid).on("value", function (snapshot) {
      var userIGN = (snapshot.val().ign);
      console.log(userIGN); // WORKS - gives ign from database 
      that.setState({ ign: userIGN }); // WORKS - sets that.state.ign to ign from database 
      console.log(that.state.ign); // WORKS - gives ign from that.state 
    })
    setTimeout(() => {
      console.log(that); // WORKS - shows object that has state with ign
      console.log(that.state.ign); // WORKS NOW!!
    },30000);