【问题标题】:How to format and display JSON data using Array.map in Reactjs?如何在 Reactjs 中使用 Array.map 格式化和显示 JSON 数据?
【发布时间】:2018-10-13 08:13:12
【问题描述】:

我正在尝试显示存储为userList 状态变量的数据。我正在尝试map 每个对象并显示每个对象的nameemail 参数,但它没有在网页上显示任何内容我只能使用console.log() 查看数据。我使用displayUsers() 显示用户并使用getAllUser() 从API 端点获取数据。 我认为我的displayUsers() 函数是错误的。 代码:

import React, { Component } from 'react';
import axios, { post } from 'axios';

class App extends Component {

  constructor(props){
    super(props);
    this.state = {
          userList:[]
    }
  }

  ComponentDidMount(){
        if(window.sessionStorage.getItem("ud") !== null){
            var _userData = JSON.parse(window.sessionStorage.getItem("ud"));
            this.userDetails = _userData;
        }
        this.getAllUser();
  }

  getAllUser(){
        axios({
            method:"GET",
            url:"http://62.210.93.54:6010/api/getAllUser",
            auth:{
                username:this.userDetails.email,
                password:this.userDetails.password
            }
        }).then((response)=>{
            console.log(response.data);
            this.setState({
                userList:response.data.results
            })    
        })
  }

  displayUsers(){
        return this.state.userList.map( user => {
          return(
            <div className="item-card">
               <div className="info">    
                    <div className="username">Username: {user.name}</div>
               </div>
            <div className="del-wrap">
                <img src={require("../../images/cancel.svg")}/>
            </div>
            </div>
            );
        })
  }

  render() {
        return(
          <div className="users-wrap">
                <h1>Users</h1>
                <div className="task-content">
                    <div className="user-wrap">
                        <div className="users">
                            <div className="item-card add">
                                    <img src={require("../../images/plus.svg")} className="plus-icon" />
                                    <div className="lbl">Add a new User</div>
                             </div>

                             {this.displayUsers()}

                        </div>
                    </div>
                </div> 
          </div>
        );
    }
}

export default App;

模型架构:

   {
  "results": [
    {
      "createdBy": null,
      "updatedBy": "Ankit",
      "createdDate": 1523892363509,
      "updatedDate": 1524066767311,
      "id": "5ad4c1964417fc66067b29cf",
      "userName": "admin",
      "email": "ankit@woocation.com",
      "roles": [
        "USER"
      ]
    },
    {
      "createdBy": null,
      "updatedBy": null,
      "createdDate": 1523971940177,
      "updatedDate": 1523971940177,
      "id": "5ad5f7640ff4ec580b885a2e",
      "userName": "varun",
      "email": "varun@woocation.com",
      "roles": [
        "ADMIN"
      ]
    },
    {
      "createdBy": null,
      "updatedBy": null,
      "createdDate": 1524302563169,
      "updatedDate": 1524302563169,
      "id": "5adb02e30ff4ec53076ffbb7",
      "userName": "Rahul",
      "email": "rahul@woocation.com",
      "roles": [
        "admin"
      ]
    },
    {
      "createdBy": null,
      "updatedBy": null,
      "createdDate": 1524303894654,
      "updatedDate": 1524303894654,
      "id": "5adb08160ff4ec53076ffbbb",
      "userName": "Nandita",
      "email": "nandita@woocation.com",
      "roles": [
        "member"
      ]
    },
    {
      "createdBy": null,
      "updatedBy": null,
      "createdDate": 1524308787960,
      "updatedDate": 1524308787960,
      "id": "5adb1b330ff4ec53076ffbc2",
      "userName": "user",
      "email": "user@woocation.com",
      "roles": [
        "USER"
      ]
    },
    {
      "createdBy": null,
      "updatedBy": null,
      "createdDate": 1524327504461,
      "updatedDate": 1524327504461,
      "id": "5adb64500ff4ec53076ffbc4",
      "userName": "Rinku",
      "email": "test@woocation.com",
      "roles": [
        "admin"
      ]
    }
  ],
  "httpStatus": "OK",
  "message": "All Users response"
}

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    您需要为要返回的地图对象的根元素添加一个键。 `

    displayUsers(){
        return this.state.userList.map( user => {
          return(
            <div key={user.name} className="item-card">
               <div className="info">    
                    <div className="username">Username: {user.name}</div>
               </div>
            <div className="del-wrap">
                <img src={require("../../images/cancel.svg")}/>
            </div>
            </div>
            );
        })
      }
    

    【讨论】:

    • 我觉得这里没必要。
    • 我已经编辑了我的问题,请查看 JSON 响应模型架构我想使用 map 显示来自 JSON 对象的电子邮件和名称参数
    【解决方案2】:

    根据您的模型架构,您的用户对象包含 userNamenot name,因此您可以在 displayUsers 方法中编写 user.userName,另外一个关键参数有助于提高性能优化,您应该在迭代器返回的元素上添加一个唯一键

     displayUsers(){
            return this.state.userList.map( user => {
              return(
                <div className="item-card" key={user.id}>
                   <div className="info">    
                        <div className="username">Username: {user.userName}</div>
                   </div>
                <div className="del-wrap">
                    <img src={require("../../images/cancel.svg")}/>
                </div>
                </div>
                );
            })
      } 
    

    【讨论】:

    • 上述解决方案是否对您不起作用,我看到您没有将对象添加到结果数组中,但它应该可以工作
    • 我想从每个 JSON 对象中显示 userNameemail 所以应该是 user.userName 而不是 user.results.userName
    • 据我了解,它应该只是user.userName,因为您将response.data.results 分配给userList
    • 好的,你的答案有效,但我没有从 API 端点获得 JSON 响应,如何检查它是否是有效的 API 端点?
    • 使用 Postman chrome 扩展并检查是否得到正确响应
    【解决方案3】:

    在我编辑您的标题之前,这将是在文档中直接显示格式化 JSON 数据的便捷快捷方式。

    displayUsers = () => <pre>{JSON.stringify(this.state.userList, null, '  ')}</pre>
    

    要只显示userNameemail,请使用这样的白名单数组

    JSON.stringify(this.state.userList, ["userName", "email"], '  ')
    

    你可以阅读更多关于JSON.stringify(value[, replacer[, space]])here的信息。

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 1970-01-01
      • 2017-03-13
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 2018-09-19
      相关资源
      最近更新 更多