React中如何从复杂JSON获取指定对象?以valor_custo_fornecedor为例
从JSON接口获取detalhe.valor_custo_fornecedor的正确写法
你的代码存在几个关键问题,修正后就能正确获取目标字段:
- Axios响应数据的位置错误:服务器返回的JSON数据存在
res.data属性中,而非直接在res对象下 - 状态更新时的变量引用错误:你错误使用了
res.valorCusto,但valorCusto是你自己定义的状态变量,不是响应对象的属性 - 初始状态类型不匹配:
valor_custo_fornecedor是单一数值/字符串,用数组作为初始值不合理 - useEffect缺少依赖数组:会导致组件重复触发接口请求,陷入无限循环
修正后的代码:
import { useState, useEffect } from 'react'; import axios from 'axios'; const YourComponent = () => { // 根据字段实际类型设置初始值,比如数值用0,字符串用'',不确定用null const [valorCusto, setValorCusto] = useState(null); useEffect(() => { axios.get('MY API LINK') .then((res) => { // 从res.data中获取接口返回的JSON结构 const targetValue = res.data?.detalhe?.valor_custo_fornecedor; setValorCusto(targetValue); }) .catch((error) => { // 新增错误处理,避免请求失败导致页面报错 console.error('获取数据失败:', error); }); }, []); // 空依赖数组确保仅在组件挂载时请求一次 return ( <div> {/* 渲染获取到的值 */} 供应商成本价: {valorCusto ?? '加载中...'} </div> ); }; export default YourComponent;
额外说明:
- 代码中使用了可选链操作符
?.,如果接口返回的JSON中detalhe或valor_custo_fornecedor不存在,不会抛出错误,而是返回undefined - 建议始终添加
catch处理请求异常,避免网络错误或接口返回异常导致页面崩溃
内容的提问来源于stack exchange,提问作者Cleiton
相关产品推荐
相关产品推荐

