使用Firebase数据库时this.setState不起作用 [英] this.setState is not working when using firebase database

查看:62
本文介绍了使用Firebase数据库时this.setState不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用状态从Firebase数据库中获取价值,但我认为这样做存在一些问题.

I am using the state to get value from the firebase database but I think there is some problem while doing it.

const dbRef=firebase.database().ref().child('profiles').child(user.uid).child('displayName') 
dbRef.on('value',snapshot=>{ 
  this.setState({ profile:{ position:snapshot.val() } }) 
}) 
console.log(this.state)

推荐答案

从Firebase加载数据和设置React的状态都是异步操作.这意味着在加载数据或修改状态时,您的主代码可以继续运行.

Both loading data from Firebase and setting the state of React are asynchronous operations. This means that your main code continues to run, while the data is being loaded, or the state is being modified.

通过在当前代码中添加一些简单的日志记录语句,您可以学到很多有关此类异步代码的信息:

You can learn a lot about such asynchronous code, by adding some simple logging statements in your current code:

const dbRef=firebase.database().ref().child('profiles').child(user.uid).child('displayName') 
console.log("Before starting listener");
dbRef.on('value',snapshot=>{ 
  console.log("Got data, start to set state");

  this.setState({ profile:{ position:snapshot.val() } }, function() {
    console.log("The state has been set");
  }) 

  console.log("Started to set state");
}) 
console.log("After starting listener");

我添加到setState的新函数是在状态修改后调用的回调,类似于Firebase具有在数据返回后调用的回调的方式.数据库.

The new function I added to setState is a callback that is called after the state has been modified, similar to how Firebase has a callback that is called after the data comes back fro. the database.

运行上面的代码时,输​​出为:

When you run the above code, the output is:

开始监听之前

启动监听器后

获取数据,开始设置状态

Got data, start to set state

开始设置状态

状态已设置

这可能不是您期望的顺序,但是对于异步操作来说,这是完全正常的.一旦异步操作完成,您传入的回调函数将被从正常操作序列中调用.

This is probably not the order you expected, but it is completely normal for asynchronous operations. The callback functions you pass in get called out of the normal operating sequence, once the asynchronous operation completes.

这意味着设置状态后需要运行的任何代码(取决于数据库数据)都必须位于我在上面的代码中添加的内部回调中.

This means that any code that needs to run after the state has been set, which in turn depends on the database data, needs to be inside the inner callback that I added in my code above.

这篇关于使用Firebase数据库时this.setState不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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