我已经从Firebase数据库中检索了数据,并使用map函数更早地正确显示了这些数据。 This is the list of objects retrieved correctly
这一次,我尝试使用orderbychild检索排序后的列表,并尝试在列表上进行映射,但它不会进入map函数。 I have console logged the state which says what shows this in the picture. It seems to be and empty list, but it still has objects inside
这是文件:https://pastebin.com/RLJMpzWN
我的问题是,如何显示对象列表?
import React from "react";
import { StyleSheet, View, Text, FlatList } from "react-native";
import firebase from 'firebase/app';
export default class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
highScoreList: null,
isDataLoaded: false
}
}
componentDidMount() {
const hList = [];
const ref = firebase.database().ref('users')
ref.orderByChild('hours').on('child_added', function(snapshot) {
hList.push({
id: snapshot.key,
hours: snapshot.val().hours,
name: snapshot.val().name
});
});
this.setState({
highScoreList: hList,
isDataLoaded: true
})
}
render(){
if(this.state.isDataLoaded && this.state.highScoreList){
return (
<View style={styles.card}>
{this.state.highScoreList.map( user => <Text key = {user.key} style = {{textAlign: 'center', marginBottom: 10}}>{user.name} {user.hours}</Text>)}
</View>
)
}else{
console.log("State var tom")
return (<Text> Waiting for data</Text>)
}
}
}
const styles = StyleSheet.create({
card: {
flex: 1, flexDirection: 'row',
backgroundColor: "#fff",
paddingVertical: 20,
paddingHorizontal: 10,
borderRadius: 20,
minHeight: 333
},
text: {
fontSize: 30,
marginBottom: 20,
color: "black",
},
});
答案 0 :(得分:0)
@ Simen96我建议您将组件重构为以下形式:
constructor(props) {
super(props);
this.state = {
highScoreList: [],
isDataLoaded: false
}
}
componentDidMount() {
const ref = firebase.database().ref('users')
ref.orderByChild('hours').on('child_added', snapshot => {
this.state.highScoreList.push({
id: snapshot.key,
hours: snapshot.val().hours,
name: snapshot.val().name
});
});
}
render(){
if(this.state.highScoreList.length){
return (
<View style={styles.card}>
{this.state.highScoreList.map( user => <Text key = {user.key} style = {{textAlign: 'center', marginBottom: 10}}>{user.name} {user.hours}</Text>)}
</View>
)
}else{
console.log("State var tom")
return (<Text> Waiting for data</Text>)
}
}
由于component_id回调是异步的,并且setState不会等待该回调被触发,因此componentDidMount函数和'child_added'回调将不会顺序执行。