【问题标题】:How should I fetch firebase data in my app我应该如何在我的应用中获取 Firebase 数据
【发布时间】:2019-05-31 16:07:02
【问题描述】:

嘿,希望你没事 {id : {name:"" , image:""}} 我的意思是在获取数据并将其存储在状态后,每行都有不同的 id。

那么我怎样才能把每一行都放在一个平面列表中呢? 这是我的真实结果:

{001: {image: "http://itgsmgroup.com/dev/foo/Activites-socio-culturelles.png", name: "Activités socioculturels"}
002: {image: "http://itgsmgroup.com/dev/foo/Accompagnement-juridique.png", name: "Accopagnement juridique"}
003: {image: "http://itgsmgroup.com/dev/foo/Sante.png", name: "santé"}
004: {image: "http://itgsmgroup.com/dev/foo/Formation.png", name: "formation et inseriton"}
005: {image: "", name: "information"}}
and this how i get data 
getData() {
        firebase.database().ref('categories/').on('value', (snapshot) => {
            console.log(snapshot.val());
            this.setState({
                data: snapshot.val()
            });    
        });
    }

【问题讨论】:

    标签: json reactjs react-native


    【解决方案1】:

    expo.io snack 上查看我为工作样本制作的小吃。

        export default class App extends React.Component {
          constructor(props){
           super(props)
           /**
           * This next line is used to convert the object that you receive from Firebase to an Array 
           * which is what a FlatList expects as data
           */
          var tempListData = Object.entries(rawData).map(([key, value]) => value) 
          this.state = {
          listData: tempListData
        }
      }
    
      componentDidMount() {
        //Normally this lifecycle method is where you would dispatch a call to firebase but for 
        //demostration purposes am using static data defined above.
      }
    
      render() {
        return (
          <View style={styles.container}>
            <FlatList
              style={{flex: 1, padding: 10}}
              data={this.state.listData}
              renderItem={({item})=>(<View style={{height: 40}}><Text>{item.name}</Text></View>)}
            />
          </View>
        );
      }
    }
    

    总之,您需要将从 Firebase 获取的 json 对象转换为可以传递给 Flatlist 的数组。

    【讨论】:

    • 应该是这样的? firebase.database().ref('categories/').on('value', (snapshot) => { console.log(snapshot.val()); const tempListData = Object.entries(snapshot.val()) .map(([key, value]) => value); this.setState({ data: tempListData }); });
    猜你喜欢
    • 1970-01-01
    • 2021-02-21
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多