简体   繁体   English

无法 map 反应 js 中的多个嵌套数组数据

[英]Unable to map multiple nested array data in react js

I am confused how can I map multiple nested array of data in react and display them in a table.我很困惑我如何 map 多个嵌套数据数组做出反应并将它们显示在表格中。

The table should contain the details of the collection: title , location , description and keywords from the collection.该表应包含集合的详细信息:标题位置描述和集合中的关键字

Here is my react code这是我的反应代码

import logo from "./logo.svg";
import "./App.css";
import { useEffect, useState } from "react";
import axios from "axios";

function App() {
  const [data, setData] = useState([]);
  useEffect(() => {
    axios
      .get("https://images-api.nasa.gov/search?media_type=image")
      .then((response) => {
        setData(response.data);
      })
      .then(
        (response) => {},
        (err) => {
          console.log(err);
        }
      );
  }, []);
  console.log(data);
  return (
    <div className="App grid  place-content-center h-screen gap-24">
      <form className="">
        <label
          for="default-search"
          class="mb-2 text-sm font-medium text-gray-900 sr-only dark:text-gray-300"
        >
          Search
        </label>
        <div class="relative">
          <div class="flex absolute inset-y-0 left-0 items-center pl-3 pointer-events-none">
            <svg
              class="w-5 h-5 text-gray-500 dark:text-gray-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
              ></path>
            </svg>
          </div>
          <input
            type="search"
            id="default-search"
            class="focus:ring-0 outline-none block p-4 pl-10 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
            placeholder="Search Mockups, Logos..."
            required
          />
          <button
            type="submit"
            class="text-white absolute right-2.5 bottom-2.5 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
          >
            Search
          </button>
        </div>
      </form>
      <div class="container flex justify-center mx-auto">
        <div class="flex flex-col">
          <div class="w-full">
            <div class="border-b border-gray-200 shadow">
              <table>
                <thead class="bg-gray-50">
                  <tr>
                    <th class="px-6 py-2 text-xs text-gray-500">title</th>
                    <th class="px-6 py-2 text-xs text-gray-500">location</th>
                    <th class="px-6 py-2 text-xs text-gray-500">description</th>
                    <th class="px-6 py-2 text-xs text-gray-500">keywords</th>
                    <th class="px-6 py-2 text-xs text-gray-500">Edit</th>
                    <th class="px-6 py-2 text-xs text-gray-500">Delete</th>
                  </tr>
                </thead>
                <tbody class="bg-white">
                  {data?.collection?.items?.map((items) => {
                    {
                      items?.data?.map((item) => {
                        <tr class="whitespace-nowrap">
                          <td class="px-6 py-4 text-sm text-gray-500">
                            {item?.data?.title}
                          </td>
                          <td class="px-6 py-4">
                            <div class="text-sm text-gray-900">
                              {item?.data?.location}
                            </div>
                          </td>
                          <td class="px-6 py-4">
                            <div class="text-sm text-gray-500">
                              {item?.data?.description}
                            </div>
                          </td>
                          <td class="px-6 py-4 text-sm text-gray-500">
                            {item?.data?.keywords}
                          </td>
                          <td class="px-6 py-4">
                            <a
                              href="#"
                              class="px-4 py-1 text-sm text-white bg-blue-400 rounded"
                            >
                              Edit
                            </a>
                          </td>
                          <td class="px-6 py-4">
                            <a
                              href="#"
                              class="px-4 py-1 text-sm text-white bg-red-400 rounded"
                            >
                              Delete
                            </a>
                          </td>
                        </tr>;
                      });
                    }
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;

Here is the nested array of data.这是嵌套的数据数组。

"collection": {
        "version": "1.0",
        "href": "http://images-api.nasa.gov/search?media_type=image",
        "items": [
            {
                "href": "https://images-assets.nasa.gov/image/KSC-2009-4794/collection.json",
                "data": [
                    {
                        "center": "KSC",
                        "title": "KSC-2009-4794",
                        "location": "Kennedy Space Center, FL",
                        "nasa_id": "KSC-2009-4794",
                        "media_type": "image",
                        "date_created": "2009-08-19T00:00:00Z",
                        "description": "CAPE CANAVERAL, Fla. – In NASA Kennedy Space Center's Orbiter Processing Facility 2, workers begin removing the forward reaction control system, or FRCS, from space shuttle Endeavour's forward fuselage nose area. The FRCS provides the thrust for attitude (rotational) maneuvers (pitch, yaw and roll) and for small velocity changes along the orbiter axis (translation maneuvers). Endeavour is designated as the shuttle for the STS-130 mission, targeted for launch in February 2010.  Photo credit: NASA/Jack Pfaller"
                    }
                ],
                "links": [
                    {
                        "href": "https://images-assets.nasa.gov/image/KSC-2009-4794/KSC-2009-4794~thumb.jpg",
                        "rel": "preview",
                        "render": "image"
                    }
                ]
            },
            {
                "href": "https://images-assets.nasa.gov/image/KSC-2009-4795/collection.json",
                "data": [
                    {
                        "center": "KSC",
                        "title": "KSC-2009-4795",
                        "location": "Kennedy Space Center, FL",
                        "nasa_id": "KSC-2009-4795",
                        "media_type": "image",
                        "date_created": "2009-08-19T00:00:00Z",
                        "description": "CAPE CANAVERAL, Fla. – In NASA Kennedy Space Center's Orbiter Processing Facility 2, a worker removes the forward reaction control system, or FRCS, from space shuttle Endeavour's forward fuselage nose area. The FRCS provides the thrust for attitude (rotational) maneuvers (pitch, yaw and roll) and for small velocity changes along the orbiter axis (translation maneuvers). Endeavour is designated as the shuttle for the STS-130 mission, targeted for launch in February 2010.  Photo credit: NASA/Jack Pfaller"
                    }
                ],
                "links": [
                    {
                        "href": "https://images-assets.nasa.gov/image/KSC-2009-4795/KSC-2009-4795~thumb.jpg",
                        "rel": "preview",
                        "render": "image"
                    }
                ]
            },
            {
                "href": "https://images-assets.nasa.gov/image/KSC-2009-4798/collection.json",
                "data": [
                    {
                        "center": "KSC",
                        "title": "KSC-2009-4798",
                        "location": "Kennedy Space Center, FL",
                        "nasa_id": "KSC-2009-4798",
                        "media_type": "image",
                        "date_created": "2009-08-20T00:00:00Z",
                        "description": "CAPE CANAVERAL, Fla. – The 327-foot tall Ares I-X rocket stretches into the upper regions of NASA Kennedy Space Center's Vehicle Assembly Building.  The rocket is stacked on the mobile launcher platform in High Bay 3.  Mission, program and NASA decals are lined up on the stack below the U.S. flag.  Five super stacks make up the upper stage that are integrated with the four-segment solid rocket booster first stage below.  Ares I-X is the test vehicle for the Ares I, which is part of the Constellation Program to return men to the moon and beyond. The Ares I-X flight test is targeted for  Oct. 31.  Photo credit: NASA/Jack Pfaller"
                    }
                ],
                "links": [
                    {
                        "href": "https://images-assets.nasa.gov/image/KSC-2009-4798/KSC-2009-4798~thumb.jpg",
                        "rel": "preview",
                        "render": "image"
                    }
                ]
            },

How can I render title , location , description and keywords from the collection from the array of data?如何从数据数组的集合中呈现标题位置描述关键字

you are not returning after mapping, for example this WILL NOT WORK :映射后您没有返回,例如这将不起作用

return (
    <div className="App">
      {data.items.map((e) => {
        <div>
          {e.data.map((s) => (
            <div>
              <div>{s.title}</div>
              <div>{s.location}</div>
            </div>
          ))}
        </div>;
      })}
    </div>
  )

ESLINT will through a warning says Expected to return a value in arrow function. (array-callback-return) ESLINT 将通过警告说Expected to return a value in arrow function. (array-callback-return) Expected to return a value in arrow function. (array-callback-return) that means you need either to add a return statement after the map or remove the curly brackets {} . Expected to return a value in arrow function. (array-callback-return)这意味着您需要在映射后添加return语句或删除大括号{} for example solution A remove curly brackets :例如解决方案 A删除大括号:

return (
    <div className="App">
      {data.items.map((e) => 
        <div>
          {e.data.map((s) => (
            <div>
              <div>{s.title}</div>
              <div>{s.location}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );

solution B add the return statement:方案B添加return语句:

return (
    <div className="App">
      {data.items.map((e) => {
        return (
          <div>
            {e.data.map((s) => {
              return (
                <div>
                  <div>{s.title}</div>
                  <div>{s.location}</div>
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );

This is how I would map to display Titles and the URL in links/href:这就是我将 map 在链接/href 中显示标题和 URL 的方式:

(I'm using Bootstrap 5 to create a photo/gallery/grid with the pictures from href + title with a limit of 15 letters per title (.substring(0, 15)+"...") ) (我正在使用 Bootstrap 5 创建一个照片/画廊/网格,其中包含来自 href + 标题的图片,每个标题限制为 15 个字母 (.substring(0, 15)+"...") )

<div className='p-3 d-flex flex-wrap'>

    {data?.collection?.items?.map((items) => {
        return(
            <>
                {items?.links?.map((links) => {
                    console.log(links);
                    return(
    <Row className='ms-3  p-1'>
    <Col className='text-center'>                
    <img
    width={180}
    height={180}
    alt="171x180"
    src={links?.href}
    className=" border border-dark"
  />
  {items?.data?.map((data) => {
    return(
        <>
          <p>{data?.title.substring(0,15)+"..."}</p>
        </>
    )
  })}
        </Col>
        </Row>
  )})}
        </>    
        )
    })}
</div>

@Teshie, were you able to fix the mapping? @Teshie,你能修复映射吗? I'm having the same issue with the same API but haven't been able to map it.我在使用相同的 API 时遇到了同样的问题,但无法 map 它。 I'm trying to display collections.items.links.href.我正在尝试显示 collections.items.links.href。

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

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