React Native通知页条件渲染:加载时显示ActivityIndicator
解决React Native通知页面的条件渲染问题
嘿,我来帮你搞定这个加载状态的显示问题!其实思路很清晰:我们只需要根据notificationLoaded这个状态变量,来决定是显示加载指示器还是通知列表就行。
修改方案
在你的render方法里,我们可以通过条件判断来实现这个逻辑:
- 当
notificationLoaded为false时,显示ActivityIndicator(记得给它加个居中的样式,让用户能直观看到加载状态) - 当
notificationLoaded为true时,再渲染之前写好的通知列表
修改后的完整render方法
render() { const notificationList = this.state.notification.map(data => ( <View key={data.msg_id} style={styles.notification}> <View style={{ display: 'flex', flexDirection: 'row', }} > <Text style={{ color: 'green' }}><Ionicons size={20} color="green" name="ios-notifications" /></Text> <Text style={{ color: '#c9c9c9', fontSize: 15, fontWeight: 'bold', marginLeft: 5, }} > {data.date_sent} </Text> </View> <View style={styles.notificationBody}> <Text style={{ color: '#000', fontSize: 16 }}>{data.message}</Text> </View> <View style={styles.lineStyle} /> </View> )); // 核心条件渲染逻辑:加载中显示指示器 if (!this.state.notificationLoaded) { return ( <View style={styles.container}> <StatusBar style={{ height: 30 }} backgroundColor="black" /> <View elevation={5} style={styles.headers}> <Text style={{ fontSize: 25, color: 'green', textTransform: 'uppercase', fontWeight: 'bold', }} > Notification </Text> <Text style={styles.topIcon} onPress={this.GoHome}> <Ionicons name="md-home" size={25} color="black" /> </Text> </View> {/* 让加载指示器居中显示 */} <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <ActivityIndicator size="large" color="green" /> </View> </View> ); } // 加载完成后显示通知列表 return ( <View style={styles.container}> <StatusBar style={{ height: 30 }} backgroundColor="black" /> <View elevation={5} style={styles.headers}> <Text style={{ fontSize: 25, color: 'green', textTransform: 'uppercase', fontWeight: 'bold', }} > Notification </Text> <Text style={styles.topIcon} onPress={this.GoHome}> <Ionicons name="md-home" size={25} color="black" /> </Text> </View> <View style={{ flex: 1, margin: 5 }}> <ScrollView alwaysBounceVertical contentContainerStyle={{ flexGrow: 1 }} enabled bounces> {notificationList} </ScrollView> </View> </View> ); }
关键点说明
- 条件判断优先级:把加载状态的判断放在render最前面,这样加载时直接返回带指示器的页面,避免多余的组件渲染
- 加载指示器优化:用
flex:1配合justifyContent: 'center'和alignItems: 'center'让指示器在屏幕中央显示,用户体验更友好 - 状态切换逻辑:你的
Notification函数已经在请求完成后把notificationLoaded设为true,这个逻辑完全没问题,状态更新后React会自动重新渲染页面,切换到通知列表
这样修改后,用户打开页面时会先看到绿色的加载指示器,等接口返回数据后就会自动显示通知列表啦!
内容的提问来源于stack exchange,提问作者Lewa Bammy Stephen
相关产品推荐
相关产品推荐

