You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

关键点说明

  1. 条件判断优先级:把加载状态的判断放在render最前面,这样加载时直接返回带指示器的页面,避免多余的组件渲染
  2. 加载指示器优化:用flex:1配合justifyContent: 'center'和alignItems: 'center'让指示器在屏幕中央显示,用户体验更友好
  3. 状态切换逻辑:你的Notification函数已经在请求完成后把notificationLoaded设为true,这个逻辑完全没问题,状态更新后React会自动重新渲染页面,切换到通知列表

这样修改后,用户打开页面时会先看到绿色的加载指示器,等接口返回数据后就会自动显示通知列表啦!

内容的提问来源于stack exchange,提问作者Lewa Bammy Stephen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:38:45