繁体   English   中英

React Native Hooks:无法在 useEffect function 的 return() 中显示值

[英]React Native Hooks: unable to display values in return() from useEffect function

将反应钩子与 firebase 实时数据库与我第一次从事的项目一起使用,正在检索数据并记录在控制台中。 但我无法将 go 移出 useEffect function 以在屏幕上显示值! 真的很感激一些帮助!

videoArray 需要放在 FlatList 中,正如您在下面的代码中看到的那样 videoArray 在控制台中的 useEffect function 中记录值。 但是,一旦我将 function 移出以将其添加到 FlatList 中,它就是 null,因为这些值位于本地 function 中。

我的问题是,我如何将 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
    });
  }, []);

似乎您正在尝试更新 State 挂钩( videoArray ),但您的操作方式错误(不应直接修改)。 相反,请使用您使用 Hook 创建的setVideo更新方法( let [videoArray, setVideo] = useState([]); ):

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

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

查看Using the Effect Hook以获取有关如何使用此特定挂钩的更多信息(通过跳过效果优化性能部分可能特别有趣)。

本质上,此功能类似于功能组件的有状态对应物( React.ComponentReact.PureComponent ),其中:

构造函数是唯一应该直接分配 this.state 的地方。 在所有其他方法中,您需要改用 this.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>
    );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM