变量的内容是[object Undefined]

时间:2017-11-04 01:03:03

标签: javascript android react-native firebase-realtime-database react-native-flatlist

问题 我正在使用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"

有用的警告消息 [![警告] [2]] [2] VirtualizedList:缺少项目的键,确保在每个项目上指定随机键属性或提供自定义keyExtractor。< / p>

2 个答案:

答案 0 :(得分:0)

您尝试在设置之前从状态中提取firebaseItems(由于查询响应的延迟),因此这将引发错误。要解决此问题,请声明它是构造函数中的状态变量。 EG

export default class App extends React.Component {
  ...
  constructor(props) {
    super(props);
    this.state = { 
       postInput: "",
       firebaseItems: [],
    }
  }

答案 1 :(得分:0)

看起来你还没有设置一些变量,你想要扩展当前的代码:

state = {
    fontLoaded: false,
  };

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