简体   繁体   English

无法从 firestore 数据库读取数据以对本机项目做出反应

[英]Cannot read data from firestore database to react native project

I am relatively new to react natuve and I am reading data from my firestore db and I can see the title and id in my console after: console.log(doc.id, doc.data());我是 React natuve 的新手,我正在从我的 firestore 数据库中读取数据,之后我可以在我的控制台中看到标题和 ID:console.log(doc.id, doc.data());

but the items dont show in my flatlist and it just displays a constant loading symbol但是这些项目没有显示在我的平面列表中,它只是显示一个恒定的加载符号

this is my code and i cannot figure out why it wont load into my flatlist.这是我的代码,我不明白为什么它不会加载到我的平面列表中。 Any help is appreciated `任何帮助表示赞赏`

import { Pressable, Text, TextInput, View, StyleSheet,
SafeAreaView, FlatList, ActivityIndicator } from 'react-native'
import React, { useState, useEffect } from 'react'
import Exercise from '../../components/Exercise'
import { MaterialIcons } from '@expo/vector-icons'; 
import { auth, app, db, getFirestore, collection, addDoc, getDocs } from '../../firebase'


const WorkoutScreen = () => {
  
  const [exerciseTitle, setTitle] = useState('');
  const [exerciseList, setExerciseList] = useState([]);

  const addExercise = async() => {
    try {
      const docRef = await addDoc(collection(db, "Exercise"), {
        title: exerciseTitle,
        isChecked: false,
      });
      console.log("Document written with ID: ", docRef.id);
      setTitle("");
    } catch (e) {
      console.error("Error adding document: ", e);
    }
  };

  const getExercise = async() => {
    const querySnapshot = await getDocs(collection(db, "Exercise"));
    querySnapshot.forEach((doc) => {
      console.log(doc.id, doc.data());
      setExerciseList({
        ...doc.data(),
        id: doc.id,
        title: doc.exerciseTitle,
      });
    });
  };

  useEffect ( () => {
    getExercise();
  }, []);
  
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}> 
      {/* heading */}
        <Text style={styles.heading}>Workout List</Text>
      {/* shopping items  */}
        <Text style={styles.noOfExercises}>0</Text>
      {/* delete all  */}
        <Pressable>
        <MaterialIcons name="delete" size={32} color="black" />
        </Pressable>  
      </View>
        {exerciseList.length > 0 ? (
        <FlatList
          data={exerciseList}
          renderItem ={({item}) => <ExerciseItem title={item.exerciseTitle}/>}
          keyExtractor={(item) => item.id}
        />
      ) : (
        <ActivityIndicator />
      )}
        <TextInput
        placeholder='Enter Excercise' 
        style={styles.input} 
        value={exerciseTitle} 
        onChangeText={(text) => setTitle(text)} 
        onSubmitEditing={addExercise} 
        /> 
      </SafeAreaView>
  )
}

export default WorkoutScreen

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  header: {
    flexDirection: 'row',
    width: '90%',
    alignSelf: 'center',
    padding: 10,
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },

  heading: {
    fontWeight: '900',
    fontStyle: 'bold',
    fontSize: 30,
    flex: 1,
    marginTop: 20,
  },

  noOfExercises: {
    fontSize: 20,
    fontWeight: '500',
    marginRight: 20,
  },

  input: {
    backgroundColor: 'lightgrey',
    padding: 10,
    fontSize: 17,
    width: '90%',
    alignSelf: 'center',
    marginTop: 'auto',
    borderRadius: 10,

  }
})

` `

The problem is here:问题在这里:

setExerciseList({
  ...doc.data(),
  id: doc.id,
  title: doc.exerciseTitle,
}); 

You're setting exerciseList to be an object, yet your rendering code expects it to be an array:您将exerciseList设置为 object,但您的呈现代码期望它是一个数组:

{exerciseList.length > 0 ? ...

Since you don't define a length property in the object, it ends up always render the <ActivityIndicator /> .由于您没有在 object 中定义length属性,因此它最终总是呈现<ActivityIndicator />

What you'll want to do is set the entire array of documents in the state, for example with:您要做的是在 state 中设置整个文档数组,例如:

const getExercise = async() => {
  const querySnapshot = await getDocs(collection(db, "Exercise"));
  setExerciseList(querySnapshot.docs.map((doc) => {
    return { ...doc.data(), id: doc.id };
  });
};

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

相关问题 使用 React Native 在平面列表中 Firestore 数据 - Firestore data in a flatlist with react native React Native 如何从 Firebase Firestore 获取数组数据? - React Native how to fetch Array data from Firebase Firestore? React Native 中来自 Firebase Firestore 的重复数据 - Duplicated data coming from Firebase Firestore in React Native 从 flutter 应用程序在 firestore 中更新数据后无法读取数据 - Cannot read data after updating it in firestore from flutter app 如何在 React Native 中使用 Firestore 数据库进行用户过滤? - How to user filter with Firestore database in React Native? 无法在反应中将数据从表单发送到 firestore 数据库 - unable to send data from form to firestore database in react React:从 Firebase Firestore 数据库导出数据的按钮 - React: Button to export data from Firebase Firestore database React Native Firebase Firestore 数据未正确获取 - React Native Firebase Firestore data not fetching properly 无法从 React-Native-Firebase(v6) Firestore 获取数据:undefined 不是函数(靠近“...this._firestore.native.collectionGet...”) - Can't get data from React-Native-Firebase(v6) Firestore: undefined is not a function (near '...this._firestore.native.collectionGet...') 从 Firestore 参考中读取数据 - Read data from Firestore reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM