简体   繁体   English

显示具有多个对象的数组值

[英]Display array value with multiple objects

I need to display the values in my UsersData array, same as array numbers, but I can not do that in ReactJS. 我需要在UsersData数组中显示与数组编号相同的值,但是我无法在ReactJS中做到这一点。

Here's an example available in CodeSandbox. 这是CodeSandbox中可用的示例。

https://codesandbox.io/s/n08n2m7mpj https://codesandbox.io/s/n08n2m7mpj

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const usersData = [
    {
      total: 3,
      data: [
        { id: 1, name: "Tania", username: "floppydiskette" },
        { id: 2, name: "Craig", username: "siliconeidolon" },
        { id: 3, name: "Ben", username: "benisphere" }
      ]
    }
  ];

  const numbers = [1, 2, 3, 4, 5];

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      {numbers.map((number, index) => (
        <li key={index}>{number}</li>
      ))}

      {usersData.length > 0 ? (
        usersData.map((data, index) => <div key={index}>Nome: {data.name}</div>)
      ) : (
        <div>No users </div>
      )}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

1) usersData is an array containing one element (an object) 1) usersData是一个包含一个元素(一个对象)的数组

2) You need to iterate over the data array of that object and display the value of name property for each its objects. 2)您需要遍历该对象的数据数组,并显示每个对象的name属性值。

{usersData[0].data.length > 0 ? (
  usersData[0].data.map((obj, index) => <div key={index}>Nome: {obj.name}</div>)
) : (
  <div>No users </div>
)}

Forked update 分叉更新

Your usersData is an array usersData=[] which contains an object usersData=[{}] which itself contains the array of data usersData=[{data: []}] so you need to change your variable to an object and use the map function on the array of data inside it like so 您的usersData是一个数组usersData = [],其中包含一个对象usersData = [{}],其本身包含数据usersArray = [{{data:[]}]]的数组,因此您需要将变量更改为对象并使用映射像这样对其中的数据数组起作用

    const usersData = {
      total: 3,
      data: [
        { id: 1, name: "Tania", username: "floppydiskette" },
        { id: 2, name: "Craig", username: "siliconeidolon" },
        { id: 3, name: "Ben", username: "benisphere" }
      ]
    };

and your loop would become 然后你的循环就会变成

      {usersData.data.length > 0 ? (
        usersData.data.map((user, index) => <div key={index}>Nome: {user.name}</div>)
      ) : (
        <div>No users </div>
      )}

You need to do 你需要做

  usersData[0].data.map(({name}, index) => <div key={index}>Nome: {name}</div>)

Becaise you are not accessing the data array in your code above 因为您没有在上面的代码中访问数据数组

usersData.map((userData, index) => {
     return userData.data.map(item => {
         return <div key={index + item.id}>Nome: {item.name}</div>;
     });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM