簡體   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

我將包括照片以及我的代碼。 我不知道我做錯了什么,但我希望能夠在他們的個人資料頁面上打印當前用戶的姓名,如圖所示。 非常感謝! 似乎永遠無法訪問快照以嘗試將字段檢索到可以使用的位置。 我已經堅持了一個星期,不知道還能嘗試什么。 我覺得這是我遺漏的一個簡單修復,但無法確定它是什么。

火店圖片

img_firestore

應用圖片

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;

在返回結果之前,所有這些都得到渲染,您需要包含useEffect並從 useEffect 函數內部運行您的 firebase。

是一個相當不錯的博客,將有助於理解鈎子。

像這樣的東西(未經測試);


 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM