我正在使用componentDidMount在React-Native App中显示Firebase实时数据,但是,当我第一次渲染时,没有显示数据。我需要返回并再次导航到页面以更新数据并显示在屏幕上。如何解决此问题并在第一次尝试时显示数据?谢谢。
import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';
import Background from "../components/Background";
import firebase from '@firebase/app'
import { ScrollView } from 'react-native-gesture-handler';
export default class ForthPage extends Component{
constructor() {
super()
this.state = {
reservas:[],
}
}
componentDidMount() {
const readUsersData = ()=> {
const nameRef = firebase.database().ref('user0001')
nameRef.on('value', (snapshot)=> {
const state = snapshot.val()
this.state.reservas = state
})
}
readUsersData()
const pushAdminData = (data) => {
this.setState({ data })
}
pushAdminData(this.state.reservas);
}
render(){
const reservas = JSON.stringify(this.state.reservas);
const { navigate } = this.props.navigation;
return (
<Background>
<View>
<ScrollView>
<Text> Mis reservas: {reservas}</Text>
<Button
color= 'orange'
title= 'Ir al Menu Principal'
onPress={() =>
{navigate('mainPage')}
}
>
</Button>
</ScrollView>
</View>
</Background>
)
}
}
readUsersData()
函数的调用似乎不清楚。尝试在与render,componentDidMount相同的级别定义函数。如下所示