首页 > 解决方案 > 无法在反应中映射哈希图

问题描述

我正在尝试使用存储在apiValidation中的哈希图的内容,如下所示:

{
  overall : {
    'corect':'40%',
    'incorect': '10%',
    'incert' : '50%',
  },
  forEachCategory: {
    'Organizational' : {
      'corect':'40%',
      'incorect': '10%',
      'incert' : '50%',
    },
    'Tehnic':{
      'corect':'40%',
      'incorect': '10%',
      'incert' : '50%',
    }
  }
  Organizational : {
    'Question 1' : [answer1,answer2,answer3]
    'Question 2' : [answer1,answer2,answer3]
  }
  scores : {
    'Tehnic' : {
      'question1' : 50,
      'question2' : 100,
      'question3' : 0,
    },
  }
}

我试图访问这样的数据,但它不会工作:

Object.keys(apiValidation).forEach((overall,forEachCategory, Organizational, scores) => {
                                <>
                                {Object.keys(apiValidation[overall]).forEach((corect,incorect,incert) => {
                                    <>
                                    <h1>Overall</h1>
                                    <p>{apiValidation[overall][corect]}</p>
                                    <p>{apiValidation[overall][incorect]}</p>
                                    <p>{apiValidation[overall][incert]}</p>
                                    </>
                                })}
                                </>
                            })
                        }

有谁知道我该怎么做?我想准确地显示内容是如何由 api 返回的。

标签: reactjsreact-native

解决方案


您在外循环中有错误。forEach 和 map 循环语法如下。


Object.keys(object).forEach((key,index) => {
   ...
})

这些循环不会像您尝试使用的那样解压缩数组中的变量。在渲染组件时也可以尝试使用 map,因为 forEach 不会返回任何内容——这意味着它不会渲染任何你想要的组件或 JSX 元素——而 map 会。因此,在您的情况下给您一个想法:

Object.keys(apiValidation).map(key => {
    return nestedElements // Didn't write the logic for this but I hope you get what I mean
}

推荐阅读