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

格式化API返回数据时控制台输出undefined/null问题排查

解决方案

1. 先确认API返回的真实结构

你的格式化函数直接假设数据路径是data.current.data[0],但如果API返回的结构和这个不匹配,就会直接解构失败。先在代码里加日志打印真实数据:

  • 在requestAPI的res.json()后加console.log("API返回数据:", data)
  • 或者在currentDataFormat开头加console.log("传入格式化函数的数据:", data)

根据真实的返回结构调整解构路径,这是最常见的问题原因。

2. 优化异步代码逻辑

getCurrentData里混用了await和.then(),虽然语法合法,但容易搞混执行顺序,改成统一的await风格更清晰:

export async function getCurrentData() {
    try {
        const rawData = await requestAPI("current", { city: "london,UK" });
        return currentDataFormat(rawData);
    } catch(err) {
        console.error(err);
        return null;
    }
}

3. 给解构加安全防护

即使API结构正确,也可能存在字段缺失的情况,直接嵌套解构会报错导致返回undefined。用可选链?.和默认值来避免:

function currentDataFormat(data) {
    // 先确认目标数据存在
    const targetItem = data?.current?.data?.[0];
    if (!targetItem) {
        console.warn("找不到需要格式化的目标数据");
        return null;
    }

    // 给嵌套的weather设置默认空对象,避免解构失败
    const {
        weather: { icon, description } = {},
        city_name, country_code, datetime, lat, lon, sunrise, sunset, temp, wind_spd
    } = targetItem;

    return {
        icon, description, city_name, country_code, datetime, 
        lat, lon, sunrise, sunset, temp, wind_spd
    };
}

4. 修复API请求的错误处理

requestAPI里的catch直接返回错误,但如果请求返回4xx/5xx状态码,fetch不会触发catch,需要手动检查响应状态:

function requestAPI(infoType, searchParams) {
    const url = new URL(API_URL + infoType);
    url.search = new URLSearchParams({ ...searchParams, key: API_KEY });

    return fetch(url)
        .then(res => {
            // 判断响应是否成功
            if (!res.ok) {
                throw new Error(`请求失败,状态码:${res.status}`);
            }
            return res.json();
        })
        .catch(err => {
            console.error("API请求出错:", err);
            // 抛出错误让上层的try/catch捕获,而不是直接返回
            throw err;
        });
}

5. 验证组件中的数据返回

在组件的getData里打印每个请求的结果,确认哪一步没有拿到数据:

async function getData() {
    try {
        const hourlyData = await getHourlyData();
        const dailyData = await getDailyData();
        const currentWeatherData = await getCurrentData();
        
        // 打印结果排查问题
        console.log("小时数据:", hourlyData);
        console.log("日数据:", dailyData);
        console.log("当前数据:", currentWeatherData);
        
        setData({ hourly: hourlyData, daily: dailyData, current: currentWeatherData });
    } catch (err) {
        console.error(err);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:07:51