调用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>
        );
    }