我是新来的反应本地人和消防员
上下文: Firestore有一个文档“ Users”,“ Location”是一个字段。
要求:我希望一个用户/已登录用户的位置显示在react本机应用程序中。 我已经编写了以下代码,但是登录后“位置”字段为空。 请提出我在哪里错了。
import React from "react";
import { Image, Button, TextInput, ScrollView, Stylesheet, Text, View } from "react-native";
import Constants from 'expo-constants';
import * as firebase from 'firebase';
import 'firebase/firestore';
constructor(props) {
super(props);
this.state = {
profileuser: [],
profileuserlocation:''
};
}
componentDidMount() {
firebase.firestore().collection('users').doc(firebase.auth().currentUser.uid).get().then(snapshot => {
let profileuserlocation = snapshot.data().Location;
this.setState({ profileuserlocation: snapshot.data().Location });
});
}
render() {
const profileuserlocation=this.state.profileuserlocation;
return (
<View>
<Text style={{ fontSize: 20, fontWeight: "bold" }}> {this.state.profileuserlocation}</Text>
</View>
)
答案 0 :(得分:2)
我知道这有点晚了,但以防万一您从未找到答案...
获取当前用户uid的标准方法是:
firebase.auth().onAuthStateChanged(user => {
if (user) {
firebaseUser = {
uid: user.uid,
name: user.displayName,//this and the email can also be got from firebaseUser
email: user.email
};
this.setState({ uid: firebaseUser.uid });
}
});
然后,如果您只想显示文档中的字段,则不需要使用快照-这确实适用于您想要继续监视字段中的更改并且使用其他方式的情况。如果您只想一次检索该字段,请使用:
const docRef = firebase.firestore().collection('users').doc(this.state.uid)
this.docRef
.doc(this.state.uid)
.get().then(function (doc) {
if (doc.exists) {
//useful ES6 'destructuring' technique for if there are many fields you are
//saving
const {
Location
} = doc.data();
this.setState({
Location
})
//or for one field you can use "this.setState({Location:doc.data().Location})"
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function (error) {
console.log("Error getting document:", error);
});
您可以在文档中找到一些很好的例子:firestore docs
希望这对某人有帮助...