【问题标题】:Render JSON data with keys from an API using map使用 map 使用 API 中的键呈现 JSON 数据
【发布时间】:2019-07-06 04:43:15
【问题描述】:

我从我的 api 获取数据,JSON 是:

{
  Teacher: 53, 
  Student: 0,
  Staff: 1, 
  Finance: 0, 
}

组件didMount时我的数据存储在我的状态 所以 this.total.users 包含我的 JSON 数据

最好的渲染方式是什么?

我知道它是带键的 JSON, 所以我应该使用类似的东西

 {Object.keys(this.state.users).map((key) => (   
   <div> {key} </div>   // display Attendee, Student, Staff, Finance
 )} 

但它不起作用,因为 this.state.users 未定义 所以我发现我可以显示我的整个 JSON 对象,它适用于

 JSON.stringify(this.state.users)}

所以我想我必须混合它们,但是如何以及何时?我有点迷路了。

最后我只想让我的 JSON 显示如下:

Attendee   Student   Staff   Finance
   53         0        1        0

【问题讨论】:

    标签: reactjs dictionary render stringify


    【解决方案1】:

    您可以执行以下操作

    1. 在执行 Object.keys 之前进行条件检查,这样当 this.state.users 未定义时不会出现任何问题
    2. 使用key获取this.state.user[key]这样的值
    3. 将唯一键设置为 div,这样您就可以渲染所有用户,否则只会渲染最后一个用户

      {this.state.users && JSON.stringify(this.state.users, Object.keys(this.state.users).map((key, index) => (   
            <div key={'Key-'+index}>
                <div> {key} </div>   // display Attendee, Student, Staff, Finance
                 <div>{this.state.users[key]</div> //this will give you value
             </div>
        )))} 
      

    【讨论】:

    • 感谢您的回答!如果我接受你的答案但没有 JSON.stringify(this.state.users, 你知道为什么吗?我想理解,如果你将它字符串化,它会显示 {} 但如果我接受 juste {JSON.stringify(this .state.users)} 它显示了整个对象。
    猜你喜欢
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 2021-04-07
    • 2021-10-20
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多