【问题标题】:REACT AXIOS not showing nested itemsREACT AXIOS 不显示嵌套项
【发布时间】:2020-02-26 08:31:34
【问题描述】:

我正在尝试阅读以下回复中的 Midnight 项目 假设它是 data.timings.Midnight ,但它没有显示在我的反应中。 有没有遍历这些嵌套项并显示它们?

HTTP/1.1 200 OK
{
   "code": 200,
   "status": "OK",
   "data": [{
       "timings": {
           "s": "03:57",
           "Ss": "05:46",
           "Dh": "12:59",
           "Asr": "16:55",
           "Sun": "20:12",
           "Mag": "20:12",
           "Is": "22:02",
           "DATAIMintested": "03:47",
           "Midnight": "00:59"
       },
       "date": {
           "readable": "24 Apr 2014",
           "timestamp": "1398332113",
           "gregorian": {
               "date": "15-05-2018",
               "format": "DD-MM-YYYY",
               "day": "15",
               "weekday": {
                   "en": "Tuesday"
               },
               "month": {
                   "number": 5,
                   "en": "May",
               },
               "year": "2018",
               "designation": {
                   "abbreviated": "AD",
                   "expanded": "Domini",
               },

【问题讨论】:

  • 数据是一个数组,它没有计时属性(虽然它包含有的对象)。

标签: reactjs axios


【解决方案1】:

您在响应中得到一个数组。我假设您想访问数组中的第零个元素。你可以这样做

Axios.get('<your url>')
.then(res => {
  const responseData = res.data;
  if(responseData && responseData.length > 0){
    const midnight = responseData[0].timings.Midnight;
    ...
     ...
  }
})
.catch(...)

【讨论】:

  • 谢谢我不应该使用 map() 吗?另外,如果我需要访问多个项目怎么办?比如公历日期和工作日?
  • 我不能只使用 map() 吗?迭代?还有我如何渲染()数据回来显示?
  • map 会给你一个数组。从 json 中提取值后,您可以在 UI 中显示它
【解决方案2】:

我猜它是一个对象数组,尝试使用索引访问数组的元素。类似

axios.get(url).then(resp => {
    console.log(resp.data[0].timings.Midnight);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多