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

React+TypeScript+Axios获取数据时的结构解析问题

问题分析与解决方案

核心问题是你预期的响应结构和实际返回的结构不匹配:你以为response.data是包含quotes数组的对象,但实际返回的直接就是quotes数组本身,所以访问response.data.quotes自然会得到undefined。

排查步骤与解决方案

1. 先确认db.json的真实结构

直接打开你的db.json文件,看它的结构属于下面哪一种:

情况A:db.json直接是Quote数组

[
  {"quote": "Stay hungry, stay foolish", "author": "Steve Jobs"},
  {"quote": "Life is what happens when you're busy making other plans", "author": "John Lennon"}
]

这种情况下,请求http://localhost:4000时,json-server会直接返回这个数组,response.data就是数组本身,不需要加.quotes。

对应调整TypeScript代码:

interface Quote {
  quote: string;
  author: string;
}

// 响应类型直接用Quote数组
const fetchData = async () => {
  try {
    const response = await axios.get<Quote[]>('http://localhost:4000');
    console.log(response.data); // 这里就是你要的quotes数组
    // 比如更新状态:setQuotes(response.data);
  } catch (err) {
    console.error('获取数据失败:', err);
  }
};

情况B:db.json是包含quotes字段的对象

{
  "quotes": [
    {"quote": "Stay hungry, stay foolish", "author": "Steve Jobs"},
    {"quote": "Life is what happens when you're busy making other plans", "author": "John Lennon"}
  ]
}

这种情况下,请求根路径http://localhost:4000会返回整个对象,此时response.data.quotes才是目标数组。如果还是拿到undefined,检查两个点:

  • 确认请求的URL是http://localhost:4000(不是http://localhost:4000/quotes,后者会直接返回quotes数组)
  • 调整TypeScript接口确保匹配:
    interface Quote {
      quote: string;
      author: string;
    }
    
    interface ResponseData {
      quotes: Quote[];
    }
    
    const fetchData = async () => {
      try {
        const response = await axios.get<ResponseData>('http://localhost:4000');
        console.log(response.data.quotes); // 正常拿到数组
        // setQuotes(response.data.quotes);
      } catch (err) {
        console.error('获取数据失败:', err);
      }
    };
    

2. 快速验证方法

在fetchData里先打印完整的响应数据,确认结构:

const fetchData = async () => {
  try {
    const response = await axios.get('http://localhost:4000');
    console.log('完整响应数据:', response.data);
    // 根据打印结果判断是数组还是包含quotes的对象,再对应调整代码
  } catch (err) {
    console.error('错误:', err);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:38:22