You need to enable JavaScript to run this app. React Native调用Open Weather API获取数据后无法渲染展示问题
优惠活动
大模型
产品
解决方案
定价
更多

React Native调用Open Weather API获取数据后无法渲染展示问题

问题根因

  • fetch请求链式调用逻辑错误:最后一个.then()执行console.log(data)后没有返回值,导致你赋值给data变量的是undefined,存入state的是无效数据。
  • state存储结构和取值逻辑不匹配:你调用setWeather时将数据包裹在data属性中,但页面渲染时直接从weather根层级取name、main等字段,自然无法取到对应值。
  • 首次渲染无数据兜底:初始state是空对象,接口请求完成前的渲染阶段访问weather.main.temp时,weather.main本身是undefined,访问子属性就会抛出未定义错误。
  • useEffect未配置依赖数组,会触发接口无限重复请求。

修正方案

调整请求逻辑、state存储逻辑,新增渲染兜底规则即可,修正后代码如下:

import React, { useState, useEffect } from 'react';
import { Feather } from '@expo/vector-icons';
import { styles2 } from '../../styles2';
import { View, Text } from 'react-native';

function Weather(props) {
    const  { name, key } = props;
    // 初始改为null方便判断加载状态
    const [ weather, setWeather] = useState(null);
    const [city, setCity] = useState('Lewisville');
    const API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    const URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}`;

    async function getWeather() {
      try {
        const res = await fetch(URL);
        const data = await res.json();
        console.log(data);
        // 直接存储接口返回的完整数据,不额外包一层
        setWeather(data);
      } catch (e) {
        console.log('请求天气接口失败', e);
      }
    }

    useEffect(() => {
      getWeather();
      // 加空依赖数组,仅组件挂载时请求一次;如果需要city变化时重新请求,就把city加入依赖数组
    }, [])


    return (
        <View style={styles2.weatherContainer} >
        {/* 加载状态判断,避免无数据时渲染报错 */}
        {!weather ? <Text>加载中...</Text> : 
        <View style={styles2.mainWeatherInfo}>
          <Text style={styles2.cityName}>{weather.name}</Text>
          <View style={styles2.tempInfo}>
            <Text style={styles2.mainTemp}>{(((weather.main.temp - 273.15)*9)/5).toFixed(1)}°</Text>
            {/* 加toFixed保留1位小数优化展示,不需要可以删掉 */}
          </View>
          <Text style={styles2.weatherDesc}>{weather.weather[0].description}</Text>
          {/* 这里也可以直接取接口返回的天气描述,不用写死 */}
        </View>
        }
        </View>
    )
}

export default Weather;

如果不想加加载判断,也可以直接用可选链语法兜底:{weather?.name}、{weather?.main?.temp && (((weather.main.temp - 273.15)*9)/5)},同样可以避免未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 05:06:03