Javascript 反应本机挂钩:无法在useEffect函数的return()中显示值

Javascript 反应本机挂钩:无法在useEffect函数的return()中显示值,javascript,reactjs,react-native,firebase-realtime-database,react-hooks,Javascript,Reactjs,React Native,Firebase Realtime Database,React Hooks,使用react钩子和firebase实时数据库以及Im第一次处理的项目,将在控制台中检索和记录数据。但我无法将useEffect功能移出屏幕以在屏幕上显示值!非常感谢您的帮助 videoArray需要放在一个平面列表中,正如您可以在下面的代码中看到的那样,videoArray记录console in useEffect函数中的值。但是,一旦我移出该函数以将其添加到平面列表中,它将为null,因为值位于本地函数中 我的问题是,如何将videoArray的值(在useEffect中)传递到平面列表中

使用react钩子和firebase实时数据库以及Im第一次处理的项目,将在控制台中检索和记录数据。但我无法将useEffect功能移出屏幕以在屏幕上显示值!非常感谢您的帮助

videoArray需要放在一个平面列表中,正如您可以在下面的代码中看到的那样,videoArray记录console in useEffect函数中的值。但是,一旦我移出该函数以将其添加到平面列表中,它将为null,因为值位于本地函数中

我的问题是,如何将videoArray的值(在useEffect中)传递到平面列表中

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>
    );
}
import React,{useState,useffect}来自“React”
从“react native”导入{FlatList,View,TouchableOpacity,Text,StyleSheet,SafeAreaView};
从“../components/Center”导入{Center}
从“expo av”导入{Video};
从“../firebase”导入firebase
const videoRef=firebase.database().ref('videocollation');
导出常量FeedScreen=({})=>{
let[videoArray,setVideo]=useState([]);
useffect(()=>{
videoRef.on('值',(子快照)=>{
视频阵列=[];
childSnapshot.forEach((doc)=>{
视频推送({
key:doc.key,
视频:doc.toJSON().video,
});
})    
})
//只能在此处记录值
console.log('working:',videoArray);
});
//从firebase获取视频uri(测试)
//readVideo=()=>{
//var collection=firebase.database().ref(“VideoCollationVideo”+“/video”).orderByValue();
//log('uri',集合);
// }
返回(
进料筛
{/*此处为空:需要在此处显示值*/}
{console.log(“test”,videoArray)}
{
返回(
视频:。。。
console.log('pressed')}>展开
);
}}keyExtractor={({item},index)=>index.toString()}>
);
}
试试这个:

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, setVideoArray] = useState([]);


    useEffect(() => {

        videoRef.on('value', (childSnapshot) => {
            const newVideoArray = [];
            childSnapshot.forEach((doc) => {
                newVideoArray.push({
                    key: doc.key,
                    video: doc.toJSON().video,
                });
            })    
            setVideoArray(newVideoArray);
        })

        // able to log values only here 
        console.log('working:', videoArray); 

    }, []);


    console.log('State also working :) >> ', videoArray); 


    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>
    );
}
useffect(()=>{
常量temp=[];//临时数组
videoRef.on(“值”,childSnapshot=>{
childSnapshot.forEach(文档=>{
临时推力({
key:doc.key,
视频:doc.toJSON().video
});
});
setVideo(temp);//更新状态数组
});
}, []);

似乎您正在尝试更新状态挂钩(
videoArray
),但您的方式不对(不应直接修改)。相反,使用您用钩子创建的
setVideo
update方法(
let[videoArray,setVideo]=useState([]);
):

查看更多关于如何使用这个特定钩子的信息(通过跳过效果优化性能部分可能特别有趣)

本质上,此功能类似于功能组件的有状态对应项(or),其中:

构造函数是您应该直接分配this.state的唯一位置。在所有其他方法中,都需要使用此.setState()

试试这个:

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, setVideoArray] = useState([]);


    useEffect(() => {

        videoRef.on('value', (childSnapshot) => {
            const newVideoArray = [];
            childSnapshot.forEach((doc) => {
                newVideoArray.push({
                    key: doc.key,
                    video: doc.toJSON().video,
                });
            })    
            setVideoArray(newVideoArray);
        })

        // able to log values only here 
        console.log('working:', videoArray); 

    }, []);


    console.log('State also working :) >> ', videoArray); 


    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>
    );
}
import React,{useState,useffect}来自“React”
从“react native”导入{FlatList,View,TouchableOpacity,Text,StyleSheet,SafeAreaView};
从“../components/Center”导入{Center}
从“expo av”导入{Video};
从“../firebase”导入firebase
const videoRef=firebase.database().ref('videocollation');
导出常量FeedScreen=({})=>{
让[videoArray,setVideoArray]=useState([]);
useffect(()=>{
videoRef.on('值',(子快照)=>{
const newVideoArray=[];
childSnapshot.forEach((doc)=>{
newVideoArray.push({
key:doc.key,
视频:doc.toJSON().video,
});
})    
setVideoArray(newVideoArray);
})
//只能在此处记录值
console.log('working:',videoArray);
}, []);
log('状态也在工作:)>>',videoArray);
返回(
进料筛
{/*此处为空:需要在此处显示值*/}
{console.log(“test”,videoArray)}
{
返回(
视频:。。。
console.log('pressed')}>展开
);
}}keyExtractor={({item},index)=>index.toString()}>
);
}

console.log('working:',videoArray);})中,您似乎缺少
,[];就在
return
之前,当我添加
时,那行代码可以工作。
出现语法错误。不管我是否更新了代码,我为您添加了复制粘贴示例在您的示例中
videoArray
被错误覆盖感谢您指出,我没有注意到
videoArray
中的
useffect
中有相同的变量名,您的代码给出了一个错误;“找不到变量
newVideoArray
”,如果我声明it@dreamLand70
setVideoArray(newVideoArray)
需要上线一件事:)我不能100%确定它的工作原理,但是,您声明
temp
的方式是,在保留原有值的同时,还将获得额外的结果。如果您在
.on
回调中声明它,那么firebase的触发器将完全覆盖列表
useEffect
[]
,最后相当于
componentDidMount
,并且仅在组件第一次呈现时激发是的,我知道,但在每次状态或道具更新时都会发生这种情况,如果你有不止一个呢?A.