(ReactAssign firebase快照到函数外部的变量 [英] (ReactAssign firebase snapshot to a variable outside of the function

查看:62
本文介绍了(ReactAssign firebase快照到函数外部的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的数据库中componentDidMount()中获取数据,它可以很好地与此配合使用:

componentDidMount() {
  firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) { 
      var valeur = snapshot.val();
      return valeur;
  });
  this.setState({userData:valeur});
}

我只是想知道如何将数据分配给可以在此函数之外使用的变量,我尝试了setstate并使用了我在没有任何声明的情况下声明的变量:react native可能未处理的诺言拒绝(id 0 )Typeerror:this.setState不是一个函数.谢谢

解决方案

将要传递给.then的匿名函数切换为箭头函数,以允许您使用类作用域中的this.

大量信息在其他地方这个

Hi i am trying to get the data from my database, in componentDidMount(), it works fine with this :

componentDidMount() {
  firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) { 
      var valeur = snapshot.val();
      return valeur;
  });
  this.setState({userData:valeur});
}

I just want to know how can i assign this data to a variable that can be use outside of this function, i tried setstate and using variable that i declare outside nothing work i get :react native possible unhandled promise rejection (id 0) Typeerror: this.setState is not a function. Thank you

解决方案

Switch the anonymous function that you're passing to .then to an arrow function to allow you to use the this from the class scope.

Plenty of information elsewhere on this

这篇关于(ReactAssign firebase快照到函数外部的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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