使用Firebase数据库时this.setState不起作用

编程入门 行业动态 更新时间:2024-10-26 11:30:12
本文介绍了使用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不起作用

本文发布于:2023-10-23 19:54:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   数据库   Firebase   setState

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!