如何解决调用Tab.Screen组件时未按时执行查询
我有一个使用反应导航的项目,并且正在实现一个底部标签,如下所示:
render() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={this.HomeScreen} />
<Tab.Screen name="Settings" component={this.SettingsScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
..在其中一个屏幕中调用this.HomeScreen
,然后在另一个屏幕中调用this.SettingsScreen
。
HomeScreen({ navigation }) {
const restaurants_discounts = this.restaurants_discounts();
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
<ScrollView
style={styles.scrollview}
scrollEventThrottle={200}
directionalLockEnabled={true}>
{restaurants_discounts}
</ScrollView>
</View>
</SafeAreaView >
);
}
调用下面的函数时,由于this.state.discounts
为空,因为以后再调用getdiscounts()
,因此没有可呈现的数据:
restaurants_discounts() {
return (
<View style={styles.exampleContainer}>
<Carousel
ref={c => this._slider1Ref = c}
data={this.state.discounts}
renderItem={this._renderdiscounts.bind(this)}
...
>
</Carousel>
</View>
);
}
getdiscounts() { //this is being called after `restaurants_discounts()` has been called
var ref = firestore().collection('discounts')
ref.onSnapshot((querySnapshot => {
var discounts = querySnapshot.docs.map(doc => { return { ...doc.data(),discount_id: doc.id } });
this.setState({
discounts: discounts
});
}));
}
}
getdiscounts()
在componentDidMount()
中被调用:
componentDidMount() {
this.getdiscounts();
}
解决方法
仅在定义this.state.discount时返回组件。例如:
restaurants_discounts() {
if (this.state.discounts === undefined || this.state.discounts === null)
return (<View><Text>Loading...</Text></View>);
return (
<View style={styles.exampleContainer}>
<Carousel
ref={c => this._slider1Ref = c}
data={this.state.discounts}
renderItem={this._renderDiscounts.bind(this)}
...
>
</Carousel>
</View>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。