reactjs - Can't store field value from firestore to variable
问题描述
I'm trying to store field value name read from a document in firestore users to variable userName so I can change the state value of userName. In general, how can I save field value to a variable and store it inside my component? Always, I appreciate everyone's help.
export default class Main extends Component {
state = {
currentUser: null,
userName: null
};
getName = async () => {
const { currentUser } = firebase.auth();
this.setState({ currentUser });
const uid = currentUser.uid;
let userName = null;
let docRef = await db.collection("users").doc(uid);
docRef.get().then(doc => {
userName = doc.data().name;
console.log(userName);
// this prints out "panda"
});
console.log(userName);
// this prints out null
this.setState({ userName });
};
componentWillMount() {
this.getName();
}
解决方案
较低的console.log(userName)
打印 null 因为您await
是在文档 ref 的分配上设置的,而不是在.get()
. .doc()
返回一个引用,而.get()
返回一个 Promise。
这会导致您的代码不等待由返回的 Promise.get()
并移动通过整个块,从而显示一个null
值,userName
因为 Promise 尚未解决。有几种不同的方法可以解决这个问题。一种方法是将您setState()
的块放入块内部,.then()
如下例所示:
将您更改getName()
为:
getName = async () => {
const { currentUser } = firebase.auth();
this.setState({ currentUser });
const uid = currentUser.uid;
await db
.collection("users")
.doc(uid)
.get()
.then(doc => {
if (doc && doc.exists) {
this.setState({ userName: doc.data().name });
}
});
};
我把它async/await
留在那里,以防您将在此方法中添加更多逻辑,这需要等待 firebase 查询。如果没有,您可以同时删除async
和await
。
推荐阅读
- excel - 将新的excel文件保存在单元格中指定的文件目录中
- xaml - 如何使用 WPF 设计复杂的表格
- c++ - 将具有空值的字符数组写入文件流
- google-sheets - 带通配符的 VLOOKUP 并找到第 N 次出现?
- sql - Oracle Java Concat Like 带参数
- c - 我的代码不起作用。我的 while 循环有问题
- vue.js - 在由于 VueCLI 想要运行命令“npm run serve”而生成的项目中,我收到一条错误消息“模块构建失败......”
- controller - 如何构建方法来过滤其他参数?
- json - 使用 Circe 自定义编解码器将 json 解码为案例类列表
- azure - 解压后的存档在服务器上不可用