【问题标题】:Display data in react native component | Firebase在 react native 组件中显示数据 |火力基地
【发布时间】:2021-01-08 17:53:46
【问题描述】:

我是本机反应的新手,并试图将一些数据显示到反应组件(最好是卡片)中,但现在 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"
  },
});

数据格式:

Object {
  "-MQXpKu8Zh1PCVsBLquO": Object {
    "description": "Good story.",
    "id": 0.8842625745597491,
    "name": "Subhodeep",
    "title": "Story 1 ",
  },
  "-MQXpRXS5_6m6YTZ39e0": Object {
    "description": "Good story 2.",
    "id": 0.8767685757714464,
    "name": "Sanjoy",
    "title": "Story 2",
  },
  "-MQXpX7ku-41CreQ8SOP": Object {
    "description": "Good story 3.
",
    "id": 0.9976208307830834,
    "name": "Sanchari",
    "title": "Story 3",
  },

【问题讨论】:

    标签: javascript reactjs firebase react-native firebase-realtime-database


    【解决方案1】:

    由于 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数组并为每个项目渲染一个组件:

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

    渲染中可能存在一些语法错误,但整体流程应该从这里清楚。

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多