gpt4 book ai didi

javascript - React Native 钩子(Hook) : unable to display values in return() from useEffect function

转载 作者:行者123 更新时间:2023-11-28 12:11:34 24 4
gpt4 key购买 nike

在我第一次处理的项目中使用带有 Firebase 实时数据库的 React hooks,正在检索数据并将其记录在控制台中。但我无法移出 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>
);
}

最佳答案

试试这个:

  useEffect(() => {
const temp = []; // temp array
videoRef.on("value", childSnapshot => {
childSnapshot.forEach(doc => {
temp.push({
key: doc.key,
video: doc.toJSON().video
});
});
setVideo(temp); // update state array
});
}, []);

关于javascript - React Native 钩子(Hook) : unable to display values in return() from useEffect function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61018144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com