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

React.js处理Rest API响应:解析JSON字段解决amount属性undefined报错

问题原因

你遇到的报错是因为API返回的price、service_timespan两个字段是JSON字符串格式,并非原生JS对象,直接访问.base_price属性会返回undefined,进而触发cannot read property amount of undefined错误。

解决方案

步骤1:预处理接口响应数据

拿到接口返回的服务列表后,先统一解析两个JSON字符串字段,同时添加try/catch避免JSON格式异常导致全页崩溃:

// 示例为axios请求场景,可根据你使用的请求库调整逻辑
const apiResponse = await axios.get('/你的接口地址')
const rawServices = apiResponse.data.services
const processedServices = rawServices.map(serviceItem => {
  let parsedPrice = {}
  let parsedTimespan = {}
  try {
    parsedPrice = serviceItem.price ? JSON.parse(serviceItem.price) : {}
    parsedTimespan = serviceItem.service_timespan ? JSON.parse(serviceItem.service_timespan) : {}
  } catch (e) {
    // 解析失败时用空对象兜底,避免报错
    console.error('字段解析失败', e)
  }
  return {
    ...serviceItem,
    price: parsedPrice,
    service_timespan: parsedTimespan
  }
})
// 将处理后的数据存入state用于渲染
setServices(processedServices)

步骤2:渲染时添加容错逻辑

修改渲染代码,使用可选链?.和空值合并运算符??添加属性访问容错和兜底展示:

{ services.length > 0 && services.map(( service, index ) => (
<tr key={service.id} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{service.service_name}</td>
    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{service.service_cat_id}</td>
    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{service.price?.base_price?.amount ?? '-'}</td>
    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{service.service_timespan?.duration?.length ?? '-'}</td>
    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
    <a href="#" className="text-indigo-600 hover:text-indigo-900">
        Edit
    </a>
    </td>
</tr>
))
}

如果你的项目环境不支持可选链语法,可以替换为传统的&&串联判断写法:

{ (service.price && service.price.base_price && service.price.base_price.amount) || '-' }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:15:03