如何让应用程序等待从从 Firestore 获取数据的模块获取所有数据,然后再在 react-native 中运行?



我有来自petData的数据.js从firestore获取数据

import firebase from '../fb';
import 'firebase/firestore';
const DATA = [];
firebase
.firestore()
.collection('pets')
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
DATA.push(doc.data());
});
});
module.exports = DATA;

和流行.js在运行前等待数据

import DATA from '../data/petData';
class Popular extends Component {
render() {
return (
<View style={styles.container}>
<FlatList
data={DATA}
renderItem={item => {
return (
<PetItem
navigation={this.props.screenProps}
source={item.item.source}
name={item.item.name}
info={item.item.info}
price={item.item.price}
/>
);
}}></FlatList>
</View>
);
}
}

如果我在获取所有数据之前运行,它会变成这样

是的,你应该看看 React 中的生命周期方法,在您的情况下,渲染方法在每次您设置状态时都会运行第一个,所以你应该在 didMount 方法中获取数据,该方法在您的组件挂载后运行

所以第一次预期的行为 数据为空/未定义/为空,因此平面列表不会出现

所以你应该在组件中放置一个获取数据函数DidMount((

//Popular.js
import firebase from '../fb';
import 'firebase/firestore';
class Popular extends Component {
constructor(props) {
super(props);
this.state = {
data: [], 
loading:true
}
}
ComponentDidMount(){
firebase
.firestore()
.collection('pets')
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
//DATA.push(doc.data());
this.setState({data:doc.data(), loading:false})
});
});
}
render() {
//make a loading component that appears if the data is empty 
If(this.state.loading){
return(
<ActivityIndecator size="large" />
)else{
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={item => {
return (
<PetItem
navigation={this.props.screenProps}
source={item.item.source}
name={item.item.name}
info={item.item.info}
price={item.item.price}
/>
);
}}
/>
</View>
);
}
}
}

最新更新