Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在react native component | Firebase中显示数据_Javascript_Reactjs_Firebase_React Native_Firebase Realtime Database - Fatal编程技术网

Javascript 在react native component | Firebase中显示数据

Javascript 在react native component | Firebase中显示数据,javascript,reactjs,firebase,react-native,firebase-realtime-database,Javascript,Reactjs,Firebase,React Native,Firebase Realtime Database,我是react native的新手,曾试图将一些数据显示到react组件(最好是卡片)中,但目前FlatList可以工作。我无法分解数据并显示它。应该怎么做 import React,{useState,useEffect} from 'react'; import { StyleSheet,Modal, View ,Text , ScrollView, Alert} from 'react-native'; import {IconButton ,Appbar, Card, TextInp

我是react native的新手,曾试图将一些数据显示到react组件(最好是卡片)中,但目前FlatList可以工作。我无法分解数据并显示它。应该怎么做

import React,{useState,useEffect} from 'react';
import { StyleSheet,Modal,  View ,Text , ScrollView, Alert} from 'react-native';
import {IconButton ,Appbar, Card,  TextInput ,Button ,
  } from 'react-native-paper';
  import firebase from './config';
  import { LogBox } from 'react-native';
  LogBox.ignoreLogs(['Setting a timer']);

export default function PlantATree(){
  const [modalVisible, setModalVisible] = useState(false);
  
  const [name,setName]=useState('');
  const [title, setTitle]=useState('');
  const [description, setDescription]=useState('');
  const [data, setmyData]=useState([])

  const savePost =  () =>{
       
      firebase.database()
      .ref('posts')
      .push({
        "id":Math.random(),
        "name":name,
        "title":title,
        "description":description,
        
      })
    setTimeout(()=>{
      Alert.alert("Your post is saved successfully :D")
    },1000)

  }

    useEffect(()=>{
      const data = firebase.database().ref("posts");
      data.on("value", datasnap =>{
        //console.log(Object.values(datasnap.val()));
        if(datasnap.val()){
        setmyData(datasnap.val());
        }
      })
    },[]);
    //console.log(data);
    const src= Object.keys(data);
    console.log("Hi",src);
  return (
    <ScrollView>
       <Appbar.Header>
            <Appbar.Content title="Plant a tree Initiative"/>
        </Appbar.Header>
        <IconButton
          icon="plus"
          color="crimson"
          size={30}
          onPress={() => setModalVisible(true)}
        />
      <View style={styles.centeredView}>
              {/*Modal Content Starts Here*/}
                <Modal
                  animationType="slide"
                  transparent={true}
                  visible={modalVisible}
                  >

                  <View style={styles.centeredView}>
                    <ScrollView style={styles.modalView}>
                      
                    <Appbar.Header style={{ padding:10}}>
                        <Appbar.Content title="Share your story.." />
                    </Appbar.Header>
                      <Card>
                        <Card.Content >
                          <View style={{marginLeft:0,marginRight:0,
                          }}>
                          <Card >
                         <Card.Content>
                          <TextInput
                            style={{}}
                            label="Your name...."   
                            mode="outlined"
                            value={name}
                            onChangeText={text =>{ setName(text)}} 
                          />
                          <TextInput
                            style={{}}
                            label="Story Title...."   
                            mode="outlined" 
                            value={title}
                            onChangeText={text =>{ setTitle(text)}}
                          />
                          <TextInput
                            style={styles.formcomponents}
                            label="Share your thoughts...."   
                            mode="outlined"
                            multiline={true}
                            numberOfLines={8}
                            value={description}
                            onChangeText={text =>{ setDescription(text)}}
                          
                          />
                          </Card.Content>
                          </Card>
                            </View>
                            <Card>                            
                                <Button mode="contained" style={{margin:20}} 
                                onPress={savePost}>
                                          post
                                </Button>
                                <Button mode="contained" style={{margin:20,backgroundColor:'crimson'}} onPress={() => setModalVisible(!modalVisible)}>
                                          close
                                </Button>
                            </Card>
                        </Card.Content>
                      </Card>
                    </ScrollView>
                  </View>
                </Modal>  
          </View>
    <View>
                  {/* DATA FROM FIREBASE  */}

                  <Text>{data?.description}</Text>
    </View>
  
    </ScrollView>
  )
}


  
const styles = StyleSheet.create({
  centeredView: {
      
    marginTop: 45,
    marginBottom:45,
  },

  modalView: {
    backgroundColor: "white",
    borderRadius: 20,
    
    marginTop:70,
    marginBottom:20,
    marginRight:20,
    marginLeft:20,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5
    },
  openButton: {
    backgroundColor: "#F194FF",
    borderRadius: 20,
    padding: 10,
    elevation: 2
  },
  textStyle: {
    color: "white",
    fontWeight: "bold",
    textAlign: "center"
  },
});

由于Firebase中的数据由多个节点组成,因此需要迭代结果并将每个子节点映射到新组件

我通常认为,在加载快照时,首先将其转换为数组(而不是对象)最容易做到这一点:

useEffect(()=>{
  const data = firebase.database().ref("posts");
  data.on("value", datasnap =>{
    let data = [];
    datasnap.forEach((childsnap) => {
      let val = childsnap.val();
      val["$key"] = childsnap.key;
      data.push(val);
    })
    setmyData(data);
  })
},[]);
然后在渲染代码中,我们可以循环此
数据
数组,并为每个项目渲染一个组件:

data.map((item) => <Text id={item["$key"]}>{item.description}</Text>)
data.map((item)=>{item.description})
渲染中可能会出现一些语法错误,但总体流程应该是清晰的

data.map((item) => <Text id={item["$key"]}>{item.description}</Text>)