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

React Native遍历天气API返回JSON 筛选展示当前时间后逐小时天气

React Native 逐小时天气展示问题修复方案

核心问题说明

你的代码无法渲染内容主要存在5个问题:

  • renderView 函数没有返回值,map 遍历生成的元素没有被返回给渲染层,自然无内容展示
  • 时间判断逻辑写反:你需要展示当前时间及之后的逐小时数据,应该判断 item.time_epoch >= 本地时间戳,原代码判断条件刚好相反,只会渲染已经过去的小时数据
  • 语法&标签嵌套错误:存在样式属性笔误 flexDilocaltime_eprection(应为 flexDirection)、三元表达式括号不匹配、ScrollView/View 标签闭合位置错误的问题
  • ScrollView 位置错误:将 ScrollView 写在 map 循环内会导致每一条小时数据都单独套一个横向滚动容器,不符合业务逻辑,应该把滚动容器放在遍历外层
  • 缺少加载状态判断:接口返回前 dataSource 为空,直接访问 dataSource.forecast 会触发报错阻塞渲染

修正后代码

状态初始化(补充你可能漏写的部分)

state = {
  isLoading: true,
  latitude: '',
  longitude: '',
  dataSource: null
}

渲染逻辑修正

renderView() {
  // 加载中或者数据为空时返回加载提示
  if (this.state.isLoading || !this.state.dataSource) {
    return <Text>加载中...</Text>
  }
  const localTime = this.state.dataSource.location.localtime_epoch
  const hourList = this.state.dataSource.forecast.forecastday[0].hour
  // 筛选当前及之后的小时数据
  const validHourList = hourList.filter(item => item.time_epoch >= localTime)
  
  if (validHourList.length === 0) {
    return <Text>暂无当日后续天气数据</Text>
  }

  return (
    <ScrollView horizontal={true}>
      {validHourList.map(item => (
        <View
          key={item.time_epoch}
          style={{
            flex: 1,
            flexDirection: 'row',
            textAlign: 'center',
            marginHorizontal: 10
          }}>
          <View style={{alignItems: 'center'}}>
            <Text>{item.time.split(' ')[1]}</Text>
            <Image
              source={{url: 'https:' + item.condition.icon}}
              style={{
                width: 50,
                height: 50,
                marginVertical: 10
              }}
            />
            <Text>{item.temp_c + '℃'}</Text>
          </View>
        </View>
      ))}
    </ScrollView>
  )
}

额外优化说明

  • 新增了 filter 提前筛选符合要求的小时数据,比在 map 里写三元判断逻辑更清晰
  • 给循环生成的元素加了 key 属性,符合React渲染规范,避免控制台警告
  • 调整了样式属性,将Image容器的对齐逻辑移到父节点,修正原样式不生效的问题

内容的提问来源于stack exchange,提问作者CodeLover

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 07:51:02