【问题标题】:Getting list from firebase and rendering it doesn't work从firebase获取列表并渲染它不起作用
【发布时间】:2017-11-03 03:15:49
【问题描述】:

问题 我正在创建一个带有 react native 和 firebase 的应用程序,用户可以在其中发布到 firebase,然后我的应用程序将呈现所有帖子。当我添加代码以呈现来自 firebase(平面列表)的帖子时,没有呈现任何内容。我将列表从 firebase 转换为数组,然后在平面列表中使用该数组来呈现帖子,但没有显示任何内容。我希望得到一些帮助。

代码

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 数据库图片

【问题讨论】:

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


    【解决方案1】:

    id 在您的componentWillMount 方法中有getItems(),并让它设置一个状态(例如“firebaseItems”)等。然后在您的FlatList 中让您的数据等于{this.state.firebaseItems}。一旦您收到您的信息,这将强制重新渲染。 EG

    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}.../>
    

    【讨论】:

    • 你让我在这里告诉你,如果我还有问题。我做了你在另一篇文章中建议的更改,但它仍然在帖子上显示 [object Undefined]。有一个关于需要密钥的警告(在另一篇文章中),但我不知道如何指定密钥,或者这甚至不是问题。也让我知道这是否会比较新的帖子更容易。
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2020-09-18
    • 2015-03-24
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2021-08-25
    • 2021-03-11
    相关资源
    最近更新 更多