【问题标题】:Reactjs Rest API response decode JSONReactjs Rest API 响应解码 JSON
【发布时间】:2021-10-22 17:56:56
【问题描述】:

我从 API URL 获得了一个 REST API 响应。但是我需要将响应的某些部分从 JSON 解码到 Object.Here is the Response.

在这里你可以看到priceservice_timespan这两个东西需要在JSON.parse()中。以便可以使用此值。否则,我不能使用它们。

这是我的代码

{ 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>
))
}

我收到cannot read property amount of undefined

【问题讨论】:

  • 您似乎知道JSON.parse 可以解析 JSON,那么是什么阻止您这样做呢?
  • 我认为让您感到困惑的是您收到的 JSON 字符串包含值也是 json 字符串的字段。因此,在解析完外部对象之后,这些值仍然是需要分别为 JSON.parsed 的字符串。
  • @rayhatfield 你是对的。当我使用 map 函数时,我还需要 JSON.parse 那些 json 字符串。但我无法得到它

标签: reactjs json


【解决方案1】:
{ (services || []).map(s => {
    ...s, 
    price: JSON.parse(s.price),
    service_timestamp: JSON.encode(s.service_timestamp)
  })
   .map(( service, index ) => ( your component) }

但是,如果可以,请避免将其放入组件中,因为这将在每次渲染时进行评估。如果有,请在 Api 服务中执行解析操作,当您收到响应或 useMemo

【讨论】:

    猜你喜欢
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多