【发布时间】:2020-07-15 23:49:02
【问题描述】:
在我第一次工作的项目中使用带有 firebase 实时数据库的反应钩子,正在检索数据并在控制台中记录。但是我无法移出 useEffect 函数以在屏幕上显示值!非常感谢您的帮助!
videoArray 需要放在 FlatList 中,正如您在下面的代码中看到的那样 videoArray 在控制台中的 useEffect 函数中记录值。但是,一旦我将该函数移出以将其添加到 FlatList 中,它就会为 null,因为这些值位于本地函数中。
我的问题是,我如何将 videoArray 的值(在 useEffect 中)传递到 FlatList?
import React, { useState, useEffect } from 'react'
import { FlatList, View, TouchableOpacity, Text, StyleSheet, SafeAreaView } from 'react-native';
import { Center } from '../components/Center'
import { Video } from 'expo-av';
import firebase from '../firebase'
const videoRef = firebase.database().ref('videoCollaction');
export const FeedScreen = ({ }) => {
let [videoArray, setVideo] = useState([]);
useEffect(() => {
videoRef.on('value', (childSnapshot) => {
videoArray = [];
childSnapshot.forEach((doc) => {
videoArray.push({
key: doc.key,
video: doc.toJSON().video,
});
})
})
// able to log values only here
console.log('working:', videoArray);
});
// get video uri from firebase (testing)
// readVideo = () => {
// var collection = firebase.database().ref("videoCollactionvideo" + "/video").orderByValue();
// console.log('uri', collection);
// }
return (
<SafeAreaView>
<Text>Feed Screen</Text>
{/* null here: need values to show up here*/}
{console.log(" test",videoArray)}
<FlatList
data={videoArray}
renderItem={({ item, index }) => {
return (
<View>
<Text style={{ fontSize: 35, color: 'red' }}>Video:...</Text>
<TouchableOpacity onPress={() => console.log('pressed')}><Text style={{ color: 'blue' }}>Expand</Text></TouchableOpacity>
</View>
);
}} keyExtractor={({ item }, index) => index.toString()}>
</FlatList>
</SafeAreaView>
);
}
【问题讨论】:
标签: javascript reactjs react-native firebase-realtime-database react-hooks