簡體   English   中英

顯示具有多個對象的數組值

[英]Display array value with multiple objects

我需要在UsersData數組中顯示與數組編號相同的值,但是我無法在ReactJS中做到這一點。

這是CodeSandbox中可用的示例。

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是一個包含一個元素(一個對象)的數組

2)您需要遍歷該對象的數據數組,並顯示每個對象的name屬性值。

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

分叉更新

您的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" }
      ]
    };

然后你的循環就會變成

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

你需要做

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

因為您沒有在上面的代碼中訪問數據數組

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