Получение списка из Firebase и рендеринг не работает

1

Проблема Я создаю приложение с реакцией родной и firebase, где пользователи могут отправлять сообщения в firebase, а затем мое приложение будет отображать все сообщения. Когда я добавил код для отображения сообщений из firebase (flatlist), ничего не отображает. Я конвертирую список из firebase в массив, а затем использую этот массив в flatlist для отображения сообщений, но ничего не появляется. Мне бы очень хотелось помочь.

Код

import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TextInput, ScrollView, TouchableHighlight, Button, FlatList } from 'react-native';
import { Font } from 'expo';
import * as firebase from 'firebase';


const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "candidtwo.firebaseapp.com",
  databaseURL: "https://candidtwo.firebaseio.com",
  storageBucket: "candidtwo.appspot.com",
};

const firebaseApp = firebase.initializeApp(firebaseConfig);

var fontLoaded = false;

var ref = firebase.database().ref('posts');

var newPostRef = ref.push();

var postWidth = 350;

export default class App extends React.Component {

  state = {
    fontLoaded: false,
  };



  componentDidMount() {
      Expo.Font.loadAsync({
        'JosefinSans-Regular.ttf': require('./JosefinSans-Regular.ttf'),
      });
 }
  constructor(props) {
    super(props);
    this.state = { postInput: ""}
  }

  getItems() {
    var items = [];
    var query = ref.orderByKey();
    query.once ('value', (snap) => {
      snap.forEach ( (child) => {
        items.push(childs.val());
      });
    });

    return items;
  }


  renderItem({ items, index }) {
    return  <View>
                <View style={{width: parseInt(this.state.postWidth), height: 250, backgroundColor: '#1daff1',  alignItems: 'center', justifyContent: 'center', borderRadius: 10, paddingLeft: 10, paddingRight:10}}>
                    <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', textAlign: 'center'}}>
                        {toString(reverse(items))}
                    </Text>
                </View>

                <View style={{width: parseInt(this.state.postWidth), height: 40, borderRadius: 10, backgroundColor: '#147aa8', flexDirection: 'row',paddingLeft:5}} >
                    <Image source={require('./CandidtwoImages/unlove.png')} />
                    <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                        -
                    </Text>
                    <Image source={require('./CandidtwoImages/undislike.png')} />
                    <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                        -
                    </Text>
                    <Image source={require('./CandidtwoImages/comments.png')} />
                    <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                        -
                    </Text>
                </View>
                <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
            </View>;
  }

 render() {
    return (
      <View style={styles.container}>
        <View style={styles.button}>
          <View style={{width: 1, height: 30, backgroundColor: '#e8e8e8'}} />
          <Button
            onPress={() => this.setState({ fontLoaded: true })}
            title="Press Me To Load the App After 15 Seconds!"
            color="#fe8200"
            accessibilityLabel="Get started anonymously!"
          />
        </View>

        {this.state.fontLoaded ? (
          <View style={styles.container}>
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 16 }}>
                Whats on your mind? Create a post!
            </Text>  

            <TextInput
                 style={{height:40, width: 320, borderColor: '#303030', borderWidth: 1}}
                 onChangeText={(postInput)=>this.setState({postInput})}
                 value={this.state.postInput}    
             />


    <Button
      style={{justifyContent: 'center'}}
      onPress={() => {
        newPostRef.set({ content:this.state.postInput });
        this.setState({ postInput: "Your post was succsesfully uploaded! :)" })    
      }}               
      title="   +   "
      color="#fe8200"
    />

            <ScrollView>

<Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 16 }}>
                Adjust the size of posts:
            </Text>  

            <TextInput
                 style={{height:40, width: 100, borderColor: '#303030', borderWidth: 1}}
                 onChangeText={(postWidth)=>this.setState({postWidth})}
                 value={this.state.postWidth}    
             />



               <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
               <View style={{width: parseInt(this.state.postWidth), height: 250, backgroundColor: '#1daff1',  alignItems: 'center', justifyContent: 'center',    borderRadius: 10, paddingLeft: 10, paddingRight:10}} >
         <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', textAlign: 'center'}}>
                    Why do android phones have higher inital quality than apple phones, but apple phones have a more consistent amount of quality throughout their years?
                </Text>
            </View>
               <View style={{width: parseInt(this.state.postWidth), height: 40, borderRadius: 10, backgroundColor: '#147aa8', flexDirection: 'row',paddingLeft:5}} >
            <Image source={require('./CandidtwoImages/unlove.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    3
                    </Text>
            <Image source={require('./CandidtwoImages/undislike.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    1
                    </Text>
            <Image source={require('./CandidtwoImages/comments.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    8
                    </Text>
        </View>

     <FlatList
        data={this.getItems}
        renderItem={this.renderItem}
    />
        </ScrollView>
      </View>) : (null) }
      </View>
    );
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 8,
    backgroundColor: '#e8e8e8',
    alignItems: 'center'
  },
  button: {
    flex: 1,
    backgroundColor: '#e8e8e8',
    alignItems: 'center'
  },
});

Изображение базы данных firebase Изображение 174551

Теги:
firebase
react-native
react-native-flatlist
firebase-realtime-database

1 ответ

1
Лучший ответ

id имеют getItems() в вашем методе componentWillMount и устанавливают ли оно состояние (например, "firebaseItems") или такое. Тогда в вашем FlatList ваши данные будут равны {this.state.firebaseItems}. Это приведет к повторной визуализации после получения вашей информации. НАПРИМЕР

componentWillMount(){
    this.getItems();
}

getItems(){
    var items = [];
    var query = ref.orderByKey();
    query.once ('value', (snap) => {
      snap.forEach ( (child) => {
         items.push(childs.val());
      });
    }).then(() => {
        this.setState({firebaseItems: items});
    });
}

тогда позже

   <FlatList data = {this.state.firebaseItems}.../>
  • 0
    Спасибо! это помогло мне
  • 0
    ты сказал мне сказать тебе, если у меня все еще будут проблемы. Я внес изменение, которое вы предложили в другом сообщении, и оно по-прежнему гласит [объект не определен] в сообщениях. Есть предупреждение о необходимости ключа (на другом посте), но я не знаю, как указать ключи, или если это даже не проблема. Также дайте мне знать, если это будет легче сделать над новым постом.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню