javascript - 仅在定义对象时如何运行 useEffect (和云 Firestore 查询)?
问题描述
尝试仅在定义“用户”时运行火库“onSnapshot”。起初,用户是一个空对象,后来它变成了一个带有id,名称等的对象。所以这不应该运行......但似乎这个'if'语句不起作用(firestore onSnapshot甚至会运行如果它未定义)。
如何解决这个问题?
useEffect(() => {
if (user) { //object is undefined at first, but gets defined later
const unsubscribe = firebase
.firestore()
.collection('users')
.doc(user.id) //This seems to run even when 'user' is undefined (an empty object)
.onSnapshot(snapshot => {
//...
})
return () => {
unsubscribe()
}
}
}, [])
解决方案
只需将user
作为依赖项包含在您的 useEffect 挂钩中
useEffect(() => {
if (user) {
//object is undefined at first, but gets defined later
const unsubscribe = firebase
.firestore()
.collection("users")
.doc(user.id) //This seems to run even when 'user' is undefined (an empty object)
.onSnapshot(snapshot => {
//...
});
return () => {
unsubscribe();
};
}
}, [user]);
推荐阅读
- vim - VIM:退格键在正常模式下删除,但在插入模式下不执行任何操作。
- javascript - 需要在所有屏幕尺寸上进行不寻常的导航工作
- html - InAppBrowser 离子测试浏览器不显示页面说无法获取我的网址
- sqlite - Sqlite,连接两个查询结果
- c# - C# String to DateTime 格式为 2018-05-26T00:00:00
- javascript - 使用 html 输入文件多次选择文件后的事件
- arrays - 如何在函数中使用numpy数组
- python-3.x - Python“root.after(1000, my_test)”。它每秒循环一次,但两次
- c# - Xamarin.Forms - 视频加载时使 ActivityIndicator 消失
- javascript - 如何在 Electron 中实现与 Node.JS 和 JQuery 函数兼容的多线程?