简体   繁体   English

我刚开始反应,我在尝试从 Firestore 获取数据字段以显示在我的应用程序的屏幕上时遇到了很多问题

[英]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

I am going to include photos as well as my code.我将包括照片以及我的代码。 I do not know what I am doing wrong but I wanna be able to print the current user's name on their profile page as shown in pictures.我不知道我做错了什么,但我希望能够在他们的个人资料页面上打印当前用户的姓名,如图所示。 Thanks so much!非常感谢! It seems as if it is never getting to the snapshot to try to retrieve the fields to where they can be used.似乎永远无法访问快照以尝试将字段检索到可以使用的位置。 I've been stuck on this for going on a week now and do not know what else to try.我已经坚持了一个星期,不知道还能尝试什么。 I feel like it is an easy fix that I am missing but cannot pinpoint what it is.我觉得这是我遗漏的一个简单修复,但无法确定它是什么。

Firestore picture火店图片

img_firestore

App picture应用图片

img_app

    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;

Its all getting render before the results have been returned, you need include useEffect and run your firebase from within inside the useEffect function.在返回结果之前,所有这些都得到渲染,您需要包含useEffect并从 useEffect 函数内部运行您的 firebase。

This is pretty decent blog and will help with the understanding of hooks. 是一个相当不错的博客,将有助于理解钩子。

Something like this (untested);像这样的东西(未经测试);


 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;


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试从 Firestore 中删除一些数据,但出现问题(反应) - I am trying to delete some data from firestore but there is a problem (react) 我从 firestore 获取数据,但它没有出现在我的反应本机应用程序屏幕中 - I fetch data from firestore but it's not appearing in my react native app screen 我在尝试使用 Firebase JS SDK 从 Firestore 检索数据时遇到问题 - I am having an issue when trying to retrieve data from Firestore using the Firebase JS SDK 当我从 React 应用程序中的 firestore 获取数据时发生错误 - An error occurred when I get a data from firestore in React app 我正在尝试在 github 页面上部署我的 static 反应应用程序,但我得到白屏 - I am trying to deploying my static react app on github pages but i'm getting white screen 我正在尝试从我的 sql 数据库获取数据到我的反应页面,但我的 api 返回一个空数组 - I am trying to get data from my sql database to my react page, but my api returns an empty array 我正在尝试从 firestore 中提取数据并使用 snapShot 方法将其设置为我的数组 - I am trying to pull data from firestore and set it to my array using the snapShot method React Native:我可以在控制台上打印我的数据,但是如何在我的 React Native 应用程序屏幕上显示数据? - React Native: I am able to print my data on my console, but how do i display the data on my React Native app screen? 我在我的REACT Web应用程序中集成了Greenshock的GSAP。 我收到一个错误:未定义Quint吗? - Im integrating GSAP from Greenshock, in my REACT Web App. I get an error: Quint is not defined? 我在反应 18 中遇到 i18next 问题 - Im having issues with i18next in react 18
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM