【问题标题】:how to render data fecthed from firebase database in react-native functional components如何在 react-native 功能组件中渲染从 firebase 数据库中提取的数据
【发布时间】:2021-02-05 10:40:46
【问题描述】:

我正在从控制台中的 firebase 数据库获取数据,如下所示。 [{ "isDonor": true, "name": "Nadi", "photo": "https://gre", "uid": "2ZE" }, { "email": "mmaz", "isDonor": true, "name": "Mz", "photo": "https://gra", "uid": "Cb" }] 我想为每个对象创建卡片,但是如何在一段时间后获取数据时做到这一点? 我想像这样渲染它

我检查了其他答案,但它们大多来自类组件。 我曾尝试使用useEffect 钩子但无法实现它 这是我的代码

import * as React from 'react';
import {Text, View, StyleSheet, Image} from 'react-native';
import database from '@react-native-firebase/database';

const donorsData = [];
database()
  .ref('users')
  .orderByChild('isDonor')
  .equalTo(true)
  .once('value')
  .then((results) => {
    results.forEach((snapshot) => {
      // console.log(snapshot.key, snapshot.val());
      //   console.log(snapshot.val());
      donorsData.push(snapshot.val());
    });
    //   console.log('aft', donorsData);
  });
export default function New() {
  return (
    <View style={styles.container}>
      {donorsData.map((v, i) => {
        return (
          <View
            key={v.uid}
            style={{
              backgroundColor: 'white',
              padding: 10,
              margin: 5,
              borderRadius: 10,
            }}>
            <Text>{v.name}</Text>
            <Text>{v.email}</Text>
            <Image source={{uri: v.photo}} style={{height: 150, flex: 1}} />
          </View>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ecf0f1',
    padding: 8,
    backgroundColor: 'lightblue',
  },
});

【问题讨论】:

    标签: react-native react-native-android react-native-firebase


    【解决方案1】:
    
    import React, { useState, useEffect } from "react";
    import { Text, View, StyleSheet, Image } from "react-native";
    import database from "@react-native-firebase/database";
    
    export default function New() {
      const [data, setData] = useState([]);
    
      useEffect(() => {
        const donorsData = [];
        database()
          .ref("users")
          .orderByChild("isDonor")
          .equalTo(true)
          .once("value")
          .then((results) => {
            results.forEach((snapshot) => {
              donorsData.push(snapshot.val());
            });
            setData(donorsData);
          });
      }, []);
    
      return (
        <View style={styles.container}>
          {data?.map((v, i) => {
            return (
              <View
                key={v.uid}
                style={{
                  backgroundColor: "white",
                  padding: 10,
                  margin: 5,
                  borderRadius: 10,
                }}
              >
                <Text>{v.name}</Text>
                <Text>{v.email}</Text>
                { v.photo && <Image source={{ uri: v.photo }} style={{ height: 150, flex: 1 }} />} 
              </View>
            );
          })}
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: "#ecf0f1",
        padding: 8,
        backgroundColor: "lightblue",
      },
    });
    

    【讨论】:

    • 真的很感激。谢谢❤️
    【解决方案2】:

    试试下面的代码...

    import React, { useState, useEffect } from 'react';
    import {Text, View, StyleSheet, Image} from 'react-native';
    import database from '@react-native-firebase/database';
    
    export default function New() {
    
        const [donorsData, setDonorsData] = useState([]);
        const [isLoading, setIsLoading] = useState(false);
    
        const getDataHandler = async () => {
            try {
                setIsLoading(true)
                database()
                  .ref('users')
                  .orderByChild('isDonor')
                  .equalTo(true)
                  .once('value')
                  .then((results) => {
                     setIsLoading(false);
                     const data = results.map((snapshot) => {
                        return snapshot.val()
                     });
                     setDonorsData([...data]);
                  }).catch(err => {
                     setIsLoading(false);
                  });
            } catch(err) {
                setIsLoading(false)
                console.log("error : ", err.message);
            }
        }
    
        useEffect(() => {
            getDataHandler()
        }, []);
    
        if (isLoading) {
            return (
                <View>
                    <ActivityIndicator size="large" color="black" />
                </View>
            )
        }
    
        return (
            <View style={styles.container}>
                {
                    donorsData
                        .map((v, i) => {
                            return (
                                <View
                                    key={v.uid}
                                    style={{
                                        backgroundColor: 'white',
                                        padding: 10,
                                        margin: 5,
                                        borderRadius: 10,
                                    }}
                               >
                                   <Text>{v.name}</Text>
                                   <Text>{v.email}</Text>
                                   <Image source={{uri: v.photo}} style={{height: 150, flex: 1}} />
                                </View>
                            );
                        }
                   )}
             </View>
      ); 
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            backgroundColor: '#ecf0f1',
            padding: 8,
            backgroundColor: 'lightblue',
        },
    });
    

    【讨论】:

    • 不工作。甚至 ActivityIndi​​cator 和控制台都没有显示在屏幕上
    • 你可以尝试在firebase文档结果中添加一个控制台吗...
    • 另外,尝试在 firebase 文档的 catch 块中添加一个控制台
    • 得到这个错误` [TypeError: undefined is not a function (near '...results.map...')]`
    • 尝试在firebase文档的then块中记录结果
    【解决方案3】:

    这是一个关于 useEffect 的简单工作示例,用于获取数据并根据数据显示卡片。

    世博 => https://snack.expo.io/DYrvw6hOn

    import React, {useState, useEffect} from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    import Constants from 'expo-constants';
    
    // or any pure javascript modules available in npm
    import { Card } from 'react-native-paper';
    
    
    
    export default function App() 
    {
    
    
      const [data, setData] = useState([])
    
      const sampleData = [{id:0, title:"One"}, {id:1, title: "Two"}]
    
      useEffect(() =>
      {
    
        setTimeout(() => 
        {
          setData(sampleData)
    
        }, 3000)
    
      }, [])
    
      const card = data.length > 0 
      ? data.map(item =>
      {
        return <Card style = {styles.cardStyle}>
            <Text>{item.id} - {item.title}</Text>
          </Card>
      })
      
          : <Text>Loading...</Text>
    
    
    
      return (
        <View style={styles.container}>
          
          {card}
          
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: 
      {
        flex: 1,
        justifyContent: 'center',
        paddingTop: Constants.statusBarHeight,
        backgroundColor: '#ecf0f1',
        padding: 8,
      },
      cardStyle:
      {
        backgroundColor: 'lightblue',
        padding: 20,
        margin: 20
      }
      
    });
    

    【讨论】:

      【解决方案4】:

      当您获得所需的数据时,您必须使用状态来更新组件。你的代码代码应该是这样的:

      import React, {useEffect, useState} from 'react';
      import {Text, View, StyleSheet, Image} from 'react-native';
      import database from '@react-native-firebase/database';
      export default function New() {
      const [data, setData] = useState([])
      
      const getData = async () => {
       const donorsData = [];
      database()
        .ref('users')
        .orderByChild('isDonor')
        .equalTo(true)
        .once('value')
        .then((results) => {
          results.forEach((snapshot) => {
            // console.log(snapshot.key, snapshot.val());
            //   console.log(snapshot.val());
            donorsData.push(snapshot.val());
          });
          //   console.log('aft', donorsData);
        });
      setData(donorsData)
      }
      useEffect(()=>{
       getData()
      },[])
        return (
          <View style={styles.container}>
            {data.lenght>0 && data.map((v, i) => {
              return (
                <View
                  key={v.uid}
                  style={{
                    backgroundColor: 'white',
                    padding: 10,
                    margin: 5,
                    borderRadius: 10,
                  }}>
                  <Text>{v.name}</Text>
                  <Text>{v.email}</Text>
                  <Image source={{uri: v.photo}} style={{height: 150, flex: 1}} />
                </View>
              );
            })}
          </View>
        );
      }
      

      【讨论】:

      • 它不起作用。我尝试过使用useState and useEffect,但它没有用。现在我尝试复制粘贴你的代码这次也没有用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多