React Native:在Hooks中加载数据

时间:2020-05-19 09:40:31

标签: react-native google-cloud-firestore

在React Native应用程序中从Firestore加载数据时我有一个小问题。

我的Firestore数据库中有2个集合Task和Categorie。每个任务都有一个类别。我想显示所有任务并按类别更改样式。

这是我的代码

import React, { useState, useEffect } from 'react'
import { View, Text } from 'react-native'
import { firebaseHOC } from '../Firebase'
import Todo from './Todo'

function Todos({ firebase }) {
    const [loading, setLoading] = useState(true)
    const [todos, setTodos] = useState([])

    useEffect(() => {
        const loadTodos = async () => {
            const list = []
            let listTask = []
            firebase.todos().get()
                .then((snapshot) => {
                    snapshot.forEach(doc => {
                        let task = doc.data()
                        listTask.push(task)
                    })

                    return listTask
                })
                .then((tasks) => {
                    tasks.map((task) => {
                        if (task.categorie) {
                            task.categorie.get().then((ref) => {
                                let categorie = ref.data()
                                list.push({
                                    id: task.id,
                                    tache: task.tache,
                                    categorie: categorie
                                })
                            })
                        }
                    })

                })
                .then(() => {
                    setTodos(list)
                    setLoading(false)
                }
                )
        }

        const loadAnyDatas = async () => {
            await loadTodos()
        }

        loadAnyDatas()

    }, [setTodos])

    const renderTodos = () => {
        console.log(todos)
        return todos.map(item => {
            let taskColor = ''
            switch (item.categorie) {
                case 'Personnel':
                    taskColor = '#FF5733'
                    break
                case 'Achats':
                    taskColor = '#43FF33'
                    break
                case 'Professionnel':
                    taskColor = '#3369FF'
                    break
                case 'Autres':
                    taskColor = '#F6FF33'
                    break
            }

            return <Todo todo={item} key={item.id} taskColor={taskColor} />
        })
    }

    if (loading) {
        return (

            <View>
                <Text>Chargement en cours</Text>
            </View>
        )
    } else {

        return (
            <View>
                {renderTodos()}
            </View>
        )
    }
}

export default firebaseHOC(Todos)

我的问题是我的屏幕加载了3次,而我的数据仅第一次加载。当我出现黑屏之后。

我在做什么错了?

0 个答案:

没有答案