从firebase中检索项目并在react native中动态填充



我是react native的新手,目前遇到了这个问题。我正试图从firebase和react native中获取对象列表,但我收到了错误消息";"渲染"没有返回任何内容;

我有一个嵌套的firebase调用。外部的获取组名列表,内部的获取组信息,作为对象,并为每个组调用。只有当应用程序第二次重新加载时,我才能看到组。

function GroupCard(props){
console.log("Card View")
return(
<View>
<Text>{props.name} </Text>
<Text>{props.members} Memebers</Text>
<Text>{props.meetings} Meetings</Text>
</View>
);
} 
function PopulateGroups(props){
var bool  = false;
var detail;
if(props.user){
let userId = Firebase.auth().currentUser.uid;
Firebase.database().ref('Users/'+userId).on('value', (snapshot)=>{

if(snapshot.exists){
console.log(snapshot.val().groups);
let groups = snapshot.val().groups;
if(groups!=null){
groups.map(group=>{
console.log("Group Name: "+group);
Firebase.database().ref().child('Groups').child(group).child('Group Description').on('value', (snapshot)=>{

if(snapshot.exists){
detail = snapshot.val();
console.log("Group Detail: "+ snapshot.val().groupName);
bool = true;

}
});
});
}
}
});

}
if(bool){
return(<View><GroupCard name={detail.groupName} members={detail.members.length} meetings='0'/></View>);  
}
else{
console.log("Hereeee!!!!");
return(
<View>
<Text>User Has No Groups</Text>
</View>
);
}

}
export default class Home extends React.Component {
state = {
user:false,
}

componentDidMount(){
Firebase.auth().onAuthStateChanged(user=>{
if(user){
console.log("Hello");
this.setState({user:true});
}
else{
console.log("Sign In!!!!!!!");
this.props.navigation.navigate('SignIn');
}
})

}
render(){
return(
<View>
<Button title="Settings" onPress={()=>this.props.navigation.navigate('Settings')}></Button>
<Text>Welcome to your home page</Text>
<PopulateGroups user={this.state.user}/>
</View>
)
}
};

数据是从Firebase异步加载的。当您的detail = snapshot.val()运行时,if(bool){早已完成。

因此,您需要通过使用useState挂钩或调用setState,将要渲染的数据存储在状态中。

类似这样的东西:

export default class Home extends React.Component {
state = {
user:false,
}
componentDidMount(){
Firebase.auth().onAuthStateChanged(user=>{
if(user){
this.setState({user:true});
loadGroups(user);
}
else{
this.props.navigation.navigate('SignIn');
}
})
}
function loadGroups(props){
if(props.user){
let userId = Firebase.auth().currentUser.uid;
Firebase.database().ref('Users/'+userId).on('value', (snapshot)=>{             
if(snapshot.exists){
let groups = snapshot.val().groups;
if(groups!=null){
groups.map(group=>{
Firebase.database().ref().child('Groups').child(group).child('Group Description').on('value', (snapshot)=>{
if(snapshot.exists){
this.setState({ detail: snapshot.val() });
}
});
});
}
}
}); 
}
}
render(){
return(
<View>
<Button title="Settings" onPress={()=>this.props.navigation.navigate('Settings')}></Button>
<Text>Welcome to your home page</Text>
<PopulateGroups user={this.state.user}/>
</View>
<View>
<GroupCard name={detail.groupName} members={detail.members.length} meetings='0'/>
</View>);  
)
}
};

最新更新