Javascript 消防商店接到电话
我需要一些理解和解决方案 我有一个单独的js文件,处理所有api调用 所以我想在我的主屏幕上从firestore获取数据 在then调用的Api中,我得到了数据,但在主屏幕中,我只得到了一个承诺 我尝试了一些改变,但没有任何帮助。我不明白这一点。 如何在主屏幕中获取数据 我的代码有问题吗 Api.jsJavascript 消防商店接到电话,javascript,google-cloud-firestore,promise,Javascript,Google Cloud Firestore,Promise,我需要一些理解和解决方案 我有一个单独的js文件,处理所有api调用 所以我想在我的主屏幕上从firestore获取数据 在then调用的Api中,我得到了数据,但在主屏幕中,我只得到了一个承诺 我尝试了一些改变,但没有任何帮助。我不明白这一点。 如何在主屏幕中获取数据 我的代码有问题吗 Api.js export const getCurrentUserProfile = () => { if (firebase.auth().currentUser.uid) { const
export const getCurrentUserProfile = () => {
if (firebase.auth().currentUser.uid) {
const userDocID = firebase.auth().currentUser.uid;
const docRef = db.collection('Users').doc(userDocID);
docRef.get().then((doc) => {
console.log(firebase.auth().currentUser.uid);
if (doc.exists) {
console.log(doc.data()); // return the data i need
return doc.data();
} else {
console.log('No document for this ID: undefined');
}
}).catch((error) => {
console.log('Error getting document', error);
});
}
}
HomeScreen.js
const user = getCurrentUserProfile();
console.log(user);
// And here i get this back:
Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
}
const user = getCurrentUserProfile().then(data => console.log(data));
// this return as well undefined
非常感谢您需要记住承诺是异步的,基本上它们只是承诺。如果您需要promise提供的实际数据,您有两种选择:
- 使用
().then()
- 使用
关键字()wait
docRef.get()
方法,它本身就是一个承诺,将解析为doc.data()
例如:
// option 1
const user = getCurrentUserProfile().then(data => console.log(data));
// option 2
const user = await getCurrentUserProfile();
console.log(user);
请记住,您只能在异步函数中使用
wait
。现在我遇到另一个错误。无效的钩子调用。钩子只能在函数组件的主体内部调用。但是我只需要初始化用户一次,就可以使用state访问对象。我怎么能做到
因为如果我将代码移动到组件内部,它会每秒运行一次
const [userObj, setUserObj] = useState({});
getCurrentUserProfile().then(user => {
setUserObj(user);
});
const HomeScreen = props => {
return (
<SafeAreaView style={globalStyles.container}>
<Text style={globalStyles.h1}>Home</Text>
</SafeAreaView>
)
};
const[userObj,setUserObj]=useState({});
getCurrentUserProfile()。然后(用户=>{
setUserObj(用户);
});
常量主屏幕=道具=>{
返回(
家
)
};
您好,谢谢您的回复。我尝试了一下,但在选项1上得到空值。如果我在api中删除了返回null,我会得到未定义的返回值和一个error@juri88返回前提取doc.data()时会发生什么情况?类似这样:const response=doc.data();返回响应代码>相同的错误:(TypeError:undefined不是一个对象(正在计算’(0,_Api.getCurrentUserProfile().then’)哦,等等。尝试返回整个docRef.get()语句。所以在docRef.get()…
之前放一个return
关键字,谢谢,现在我得到了数据,但只有在if console.log(user)之前;我又得到了一个承诺?为什么?你知道吗?为什么我必须归还整个doc.ref?