Data obtained from Firebase Realtime Database in React Native using Hooks is not displayed on the screen

╄→гoц情女王★ 提交于 2021-01-20 13:38:11

问题


I started using Hooks in React Native recently and I'm trying to get the data from Firebase Realtime Database and render it in FlatList. The data is being displayed on the console, in object format, but it is not working, it is not being rendered on the screen. What am I doing wrong? How do I make it work correctly?

My code:

import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, FlatList } from 'react-native';

import firebase from '@firebase/app';
import '@firebase/database';

export default function QuestList({ navigation }) {
  const title = navigation.getParam('title');
  const [data, setData] = useState([]);

  useEffect(() => {
      const db = firebase.database();
      db.ref('/questionnaires/')
        .on('value', snapshot => {
          console.log(snapshot.val());
          const data = snapshot.val();
        });
  }, []);

  return (<FlatList 
    data={data}
    renderItem={
      ({ item, index }) => (<View>
        <Text index={index}>{item.title}</Text>
      </View>)
    }
    keyExtractor={item=>item.id}
    numColumns={2}
    showsVerticalScrollIndicator={false}
    />
  );
}

回答1:


You're probably missing a setData call in your useEffect

useEffect(() => {
  const db = firebase.database();
  db.ref('/questionnaires/')
    .on('value', snapshot => {
      const response = snapshot.val();
      setData(response);
    });
}, []);


来源:https://stackoverflow.com/questions/65649985/data-obtained-from-firebase-realtime-database-in-react-native-using-hooks-is-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!