【问题标题】:Im new to react and I am having a ton of issues trying to get data fields from firestore to show up on the screen on my app我是新手,我在尝试从 firestore 获取数据字段以显示在我的应用程序屏幕上时遇到很多问题
【发布时间】:2020-11-16 05:21:08
【问题描述】:

我将包括照片以及我的代码。我不知道我做错了什么,但我希望能够在他们的个人资料页面上打印当前用户的姓名,如图所示。非常感谢!似乎它永远不会到达快照以尝试将字段检索到可以使用它们的位置。我已经坚持了一周了,不知道还能尝试什么。我觉得这是一个很容易解决的问题,但我无法确定它是什么。

Firestore 图片

应用图片

    import 'react-native-gesture-handler';
import auth, {firebase} from '@react-native-firebase/auth';
import firestore from '@react-native-firebase/firestore';
//import * as React from 'react';
import React, {useState} from 'react';

import {NavigationContainer} from '@react-navigation/native';
import {
  StyleSheet,
  Picker,
  SafeAreaView,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  Button,
} from 'react-native';
import {createStackNavigator} from '@react-navigation/stack';
import {ScrollView} from 'react-native-gesture-handler';

const Profile = ({navigation}) => {
  const [firstName, setFname] = useState('');
  const [lastName, setLname] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [age, setAge] = useState('');
  const [sex, setSex] = useState('');
  const [id, setId] = useState('');

  getUserInfo = async () => {
     firebase
      .firestore()
      .collection('users')
      .doc(firebase.auth().currentUser.uid)
      .onSnapshot((docs) => {
        setFname(docs.data().firstName);
        console.log(firstName);
        setLname({lastName: docs.data().lastName});
        setEmail({email: docs.data().email});
        setPassword({password: docs.data().password});
        setAge({age: docs.data().age});
        setSex({sex: docs.data().sex});
        setId({id: docs.data().id});
      });
  };

  

  const db = firebase.firestore();
  var user = firebase.auth().currentUser;
  var usersEmail = user.email;
  var userID = firebase.auth().currentUser.uid;


  
  
  db.collection('users')
    .where('email', '==', usersEmail)
    .get()
    .then(function (querySnapshot) {
      querySnapshot.forEach(function (doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, ' => ', doc.data());
        var data = doc.data();
        const fn = doc.get('firstName');
        setFname({firstName: fn});
        console.log(firstName);
        console.log(data);
        setFname(data.firstName);
        //var lastName = data.lastName;
        //var firstName = doc.get("first");
        //var lastName = doc.get("last");
      });
    })
    .catch(function (error) {
      console.log('Error getting documents: ', error);
    });

    
    
 

  return (
    
    <SafeAreaView style={styles.container2}>
      <ScrollView>
        <View style={styles.container}>
          <Text style={styles.logo}>Profile</Text>
          <Text style={styles.Info}>
            Name: {firstName} {lastName}  
          </Text>
          <Text style={styles.Info}>Email: {usersEmail}</Text>
          <Text style={styles.Info}>Age: </Text>
          <Text style={styles.Info}>Sex:</Text>
          <Text style={styles.Info}>Sports:</Text>
          <TouchableOpacity
            style={styles.button}
            onPress={() => navigation.navigate('EditProfile')}>
            <Text style={styles.buttonText}>Edit Profile</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.button}
            onPress={() => navigation.navigate('Messages')}>
            <Text style={styles.buttonText}>My Messages</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#2c9f45',
    alignItems: 'center',
    justifyContent: 'center',
  },
  container2: {
    flex: 1,
    backgroundColor: '#2c9f45',
    justifyContent: 'center',
  },
  button: {
    width: '85%',
    backgroundColor: '#263844',
    borderRadius: 25,
    height: 54,
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 15,
    marginBottom: 15,
  },
  buttonText: {
    color: 'white',
    fontSize: 20,
  },
  logo: {
    fontWeight: 'bold',
    fontSize: 54,
    color: '#263844',
    marginBottom: 20,
  },
  Info: {
    fontWeight: 'bold',
    fontSize: 22,
    color: '#263844',
    marginBottom: 20,
  },
});

export default Profile;

【问题讨论】:

标签: reactjs firebase react-native google-cloud-firestore


【解决方案1】:

它在返回结果之前全部渲染,您需要包含 useEffect 并从 useEffect 函数内部运行您的 Firebase。

This 是相当不错的博客,有助于理解钩子。

类似这样的东西(未经测试);


 import 'react-native-gesture-handler';
import auth, {firebase} from '@react-native-firebase/auth';
import firestore from '@react-native-firebase/firestore';
//import * as React from 'react';
import React, {useEffect, useState} from 'react';

import {NavigationContainer} from '@react-navigation/native';
import {
  StyleSheet,
  Picker,
  SafeAreaView,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  Button,
} from 'react-native';
import {createStackNavigator} from '@react-navigation/stack';
import {ScrollView} from 'react-native-gesture-handler';

const Profile = ({navigation}) => {
  const [firstName, setFname] = useState('');
  
 // const db = firebase.firestore();
 // const { email } = firebase.auth().currentUser;
const email = ‘Sprint3@test.com’;

useEffect( () => {
  db.collection('users')
    .where('email', '==', usersEmail)
    .get()
    .then(function (querySnapshot) {
      // This will step over every doc that has that email, you should limit it one and organise by an updated field. .limit(1)
      querySnapshot.forEach(function (doc) {
        const fn = doc.get('firstName');
        setFname(fn);
        
       // Add whatever states from the data you need or just one object with all the info in.
      });
    })
    .catch(function (error) {
      console.log('Error getting documents: ', error);
    });
}, []);
    
    

  return (
    
    <SafeAreaView style={styles.container2}>
      <ScrollView>
        <View style={styles.container}>
          <Text style={styles.logo}>Profile</Text>
          <Text style={styles.Info}>
            Name: {firstName} 
          </Text>
          <TouchableOpacity
            style={styles.button}
            onPress={() => navigation.navigate('EditProfile')}>
            <Text style={styles.buttonText}>Edit Profile</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.button}
            onPress={() => navigation.navigate('Messages')}>
            <Text style={styles.buttonText}>My Messages</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#2c9f45',
    alignItems: 'center',
    justifyContent: 'center',
  },
  container2: {
    flex: 1,
    backgroundColor: '#2c9f45',
    justifyContent: 'center',
  },
  button: {
    width: '85%',
    backgroundColor: '#263844',
    borderRadius: 25,
    height: 54,
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 15,
    marginBottom: 15,
  },
  buttonText: {
    color: 'white',
    fontSize: 20,
  },
  logo: {
    fontWeight: 'bold',
    fontSize: 54,
    color: '#263844',
    marginBottom: 20,
  },
  Info: {
    fontWeight: 'bold',
    fontSize: 22,
    color: '#263844',
    marginBottom: 20,
  },
});

export default Profile;


【讨论】:

  • 即使在切换到 useEffect 之后,尝试将其放在屏幕上时,它似乎也没有获得值 firstName。我把他上面的返回函数正确吗?然后应该能够在返回函数中调用'firstName'?还是我还是做错了什么?
  • useEffect 应该在 return 之上,但在导出的函数之内。我将扩展我的答案以提供帮助。
  • 这就是我拥有它的方式,它似乎与之前在返回结果之前呈现的问题完全相同。我不确定是什么原因造成的。
  • 现在检查我的答案,也检查这个帖子(这可能是重复的,stackoverflow.com/questions/64856233/…)
  • 您需要调试代码,但我注意到您在文档中的电子邮件有一个大写的刺痛,我认为这不会有帮助。我已经硬编码了电子邮件地址,看看现在会发生什么。替换 currentUser 并在它工作后进行调试。没有看到您的错误或日志将无济于事!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2021-04-06
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 2013-03-26
  • 2022-01-24
相关资源
最近更新 更多