Содержимое переменной [объект не определен]

Проблема. Я создаю простое приложение с помощью React Native и firebase, где пользователи могут публиковать сообщения в Интернете и видеть, что опубликовали другие люди. Вы можете загружать вещи на серверы, но когда вы пытаетесь визуализировать сообщения с помощью плоского списка, в сообщениях говорится [object Undefined] вместо того, что находится на сервере. Я хотел бы помочь исправить это.

Код

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: ""}
 }

  componentWillMount(){
    this.getItems();
 }

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


  renderItem({ items, index }) {
   return  <View>
                <View style={{width: 360, 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))}*/} {toString(items)}
                    </Text>
                </View>

                <View style={{width:360, 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="Get started anonymously!"
            color="#fe8200"
            accessibilityLabel="Run the app"
          />
        </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>
    <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />


     <FlatList
        data = {this.state.firebaseItems}
        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

posts:
  ipaurfiauerspfna(random example key):
    content: "hello world"
  apiergnfpiarngaenig:
    content: "test"

полезное предупреждающее сообщение [! [warning] [2]] [2] VirtualizedList: отсутствуют ключи для элементов, обязательно укажите свойство случайного ключа для каждого элемента или укажите настраиваемый keyExtractor.


comment
the posts say [object Undefined] какая строка в вашем коде дает такой результат   -  person Jaromanda X    schedule 04.11.2017
comment
@JaromandaX this.setState ({firebaseItems: items});   -  person GIISE    schedule 04.11.2017
comment
@KenWhite, мне плохо. Поменял второе изображение на предупреждение. Я думаю, что первый может быть полезен для получения контента с серверов.   -  person GIISE    schedule 04.11.2017
comment
@KenWhite Хорошо, я изменил это.   -  person GIISE    schedule 04.11.2017


Ответы (2)


Вы пытаетесь вывести firebaseItems из состояния до того, как его установили (из-за задержки ответа на запрос), поэтому это вызовет ошибку. Чтобы исправить это, объявите, что это переменная состояния в вашем конструкторе. НАПРИМЕР

export default class App extends React.Component {
  ...
  constructor(props) {
    super(props);
    this.state = { 
       postInput: "",
       firebaseItems: [],
    }
  }
person Ryan Turnbull    schedule 04.11.2017
comment
PS Я думаю, что уже отвечал на ваш вопрос раньше (я вижу некоторые из предложенных мной кодов), поэтому, если у вас все еще есть проблемы, просто прокомментируйте OP вместо того, чтобы создавать новый - person Ryan Turnbull; 04.11.2017

Похоже, вы еще не установили некоторые переменные, вам нужно расширить текущий код:

state = {
    fontLoaded: false,
  };

to

state = {
    postInput: "", // Or some other default
    fontLoaded: false,
  };
person CharlieMartell    schedule 04.11.2017