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

在React中使用axios从JSON接口返回数据中提取id值的方法咨询

问题原因

你当前的取值路径和接口返回的嵌套结构不匹配,你调用的Blibli商品搜索接口的响应里,response.data 下还嵌套了一层 data 字段,商品列表products就在这层嵌套字段中。

修正方案

你可以任选一种方式修改:

  • 方案1:修改请求成功后的赋值逻辑,直接提取业务数据层
    把.then里的赋值改为 setData(response.data.data),原有渲染逻辑{data.products[0].id}不用改动
  • 方案2:不改赋值逻辑,直接修改渲染时的取值路径
    把渲染部分的取值改为{data.data.products[0].id}

优化建议

可以用可选链操作符避免数据未加载/结构异常时的白屏报错,把取值写成{data?.data?.products?.[0]?.id}即可。

完整修正代码

import React, { useState, useEffect } from "react";
import axios from "axios";

export default function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios("https://www.blibli.com/backend/search/products?category=T--1000001")
      .then((response) => {
        // 直接提取业务数据层,后续取值更简洁
        setData(response.data.data);
      })
      .catch((error) => {
        console.error("Error fetching data: ", error);
        setError(error);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) return "Loading...";
  if (error) return "Error!";

  return (
    <>
      {/* 加可选链增强兼容性 */}
      <p>{data?.products?.[0]?.id}</p>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </>
  );
}

内容的提问来源于stack exchange,提问作者Shaiful Rizal Shaharudin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:36:03