简体   繁体   English

如何使用 React 访问嵌套的 JSON 对象数据?

[英]How do I access nested JSON object data with React?

I am working on project where I want to display results to user, but I am stuck when rendering JSON object data;我正在处理我想向用户显示结果的项目,但在呈现 JSON 对象数据时我卡住了; it gives an error state:它给出了一个错误状态:

'map' is not a function “地图”不是函数

App.js应用程序.js

import React, { useState, useEffect } from "react";
import "./App.css";
import { api } from "./data";

const App = () => {
  const [state, setState] = useState([]);
  useEffect(() => {
    setState(api);
    //console.log(state)
  }, [state]);

  const maping = () => {
    state.map((item, index) => (
      <h3 key={index}>{item}</h3>
    ))
  }

  return (
    <div className="App">
      <h3> json data rendering test</h3>
      {maping()}
    </div>
  );
};
export default App;

And here is my json data这是我的 json 数据

export const api = {
  success: true,
  count: 4,
  pagination: {},
  data: [
    {
      location: {
        type: "Point",
        coordinates: [-71.525909, 41.483657],
        formattedAddress: "45 Upper College Rd, Kingston, RI 02881-2003, US",
        street: "45 Upper College Rd",
        city: "Kingston",
        state: "RI",
        zipcode: "02881-2003",
        country: "US"
      },
      careers: [
        "Mobile Development",
        "Web Development",
        "Data Science",
        "Business"
      ],
      photo: "no-photo.jpg",
      housing: false,
      jobAssistance: true,
      jobGuarantee: true,
      acceptGi: true,
      _id: "5d725a1b7b292f5f8ceff788",
      user: "5c8a1d5b0190b214360dc032",
      name: "Devcentral Bootcamp",
      description:
        "Is coding your passion? Codemasters will give you the skills and the tools to become the best developer possible. We specialize in front end and full stack web development",
      website: "https://devcentral.com",
      phone: "(444) 444-4444",
      email: "enroll@devcentral.com",
      createdAt: "2019-11-20T10:05:07.447Z",
      slug: "devcentral-bootcamp",
      __v: 0,
      averageCost: 6340,
      courses: [
        {
          scholarshipAvailable: false,
          _id: "5d725cfec4ded7bcb480eaa7",
          title: "IOS Development",
          description:
            "Get started building mobile applications for IOS using Swift and other tools",
          weeks: "8",
          tuition: 6000,
          minimumSkill: "intermediate",
          bootcamp: "5d725a1b7b292f5f8ceff788",
          user: "5c8a1d5b0190b214360dc032",
          createdAt: "2019-11-20T10:05:11.655Z",
          __v: 0
        },
        {
          scholarshipAvailable: false,
          _id: "5d725cfec4ded7bcb480eaa6",
          title: "Software QA",
          description:
            "This course will teach you everything you need to know about quality assurance",
          weeks: "6",
          tuition: 5000,
          minimumSkill: "intermediate",
          bootcamp: "5d725a1b7b292f5f8ceff788",
          user: "5c8a1d5b0190b214360dc032",
          createdAt: "2019-11-20T10:05:11.654Z",
          __v: 0
        },
        {
          scholarshipAvailable: false,
          _id: "5d725cfec4ded7bcb480eaa5",
          title: "Web Development",
          description:
            "This course will teach you how to build high quality web applications with technologies like React, Node.js, PHP & Laravel",
          weeks: "8",
          tuition: 8000,
          minimumSkill: "beginner",
          bootcamp: "5d725a1b7b292f5f8ceff788",
          user: "5c8a1d5b0190b214360dc032",
          createdAt: "2019-11-20T10:05:11.653Z",
          __v: 0
        }
      ],
      id: "5d725a1b7b292f5f8ceff788"
    },
    {
      location: {
        type: "Point",
        coordinates: [-73.200576, 44.478305],
        formattedAddress: "85 S Prospect St, Burlington, VT 05401-3444, US",
        street: "85 S Prospect St",
        city: "Burlington",
        state: "VT",
        zipcode: "05401-3444",
        country: "US"
      },
      careers: ["Web Development", "Data Science", "Business"],
      photo: "no-photo.jpg",
      housing: false,
      jobAssistance: false,
      jobGuarantee: false,
      acceptGi: false,
      _id: "5d725a037b292f5f8ceff787",
      user: "5c8a1d5b0190b214360dc031",
      name: "Codemasters",
      description:
        "Is coding your passion? Codemasters will give you the skills and the tools to become the best developer possible. We specialize in full stack web development and data science",
      website: "https://codemasters.com",
      phone: "(333) 333-3333",
      email: "enroll@codemasters.com",
      createdAt: "2019-11-20T10:05:07.446Z",
      slug: "codemasters",
      __v: 0,
      averageCost: 10500,
      courses: [
        {
          scholarshipAvailable: false,
          _id: "5d725cfec4ded7bcb480eaa4",
          title: "Data Science Program",
          description:
            "In this course you will learn Python for data science, machine learning and big data tools",
          weeks: "10",
          tuition: 9000,
          minimumSkill: "intermediate",
          bootcamp: "5d725a037b292f5f8ceff787",
          user: "5c8a1d5b0190b214360dc031",
          createdAt: "2019-11-20T10:05:11.651Z",
          __v: 0
        },
        {
          scholarshipAvailable: false,
          _id: "5d725ce8c4ded7bcb480eaa3",
          title: "Web Design & Development",
          description:
            "Get started building websites and web apps with HTML/CSS/JavaScript/PHP. We teach you",
          weeks: "10",
          tuition: 12000,
          minimumSkill: "beginner",
          bootcamp: "5d725a037b292f5f8ceff787",
          user: "5c8a1d5b0190b214360dc031",
          createdAt: "2019-11-20T10:05:11.651Z",
          __v: 0
        }
      ],
      id: "5d725a037b292f5f8ceff787"
    },
    {
      location: {
        type: "Point",
        coordinates: [-71.324239, 42.650484],
        formattedAddress: "220 Pawtucket St, Lowell, MA 01854-3502, US",
        street: "220 Pawtucket St",
        city: "Lowell",
        state: "MA",
        zipcode: "01854-3502",
        country: "US"
      },
      careers: ["Web Development", "UI/UX", "Mobile Development"],
      photo: "no-photo.jpg",
      housing: false,
      jobAssistance: true,
      jobGuarantee: false,
      acceptGi: true,
      _id: "5d713a66ec8f2b88b8f830b8",
      user: "5d7a514b5d2c12c7449be046",
      name: "ModernTech Bootcamp",
      description:
        "ModernTech has one goal, and that is to make you a rockstar developer and/or designer with a six figure salary. We teach both development and UI/UX",
      website: "https://moderntech.com",
      phone: "(222) 222-2222",
      email: "enroll@moderntech.com",
      createdAt: "2019-11-20T10:05:07.444Z",
      slug: "moderntech-bootcamp",
      __v: 0,
      averageCost: 11000,
      courses: [
        {
          scholarshipAvailable: false,
          _id: "5d725cb9c4ded7bcb480eaa1",
          title: "Full Stack Web Dev",
          description:
            "In this course you will learn all about the front end with HTML, CSS and JavaScript. You will master tools like Git and Webpack and also learn C# and ASP.NET with Postgres",
          weeks: "10",
          tuition: 12000,
          minimumSkill: "intermediate",
          bootcamp: "5d713a66ec8f2b88b8f830b8",
          user: "5d7a514b5d2c12c7449be046",
          createdAt: "2019-11-20T10:05:11.649Z",
          __v: 0
        },
        {
          scholarshipAvailable: false,
          _id: "5d725cd2c4ded7bcb480eaa2",
          title: "UI/UX",
          description:
            "In this course you will learn to create beautiful interfaces. It is a mix of design and development to create modern user experiences on both web and mobile",
          weeks: "12",
          tuition: 10000,
          minimumSkill: "intermediate",
          bootcamp: "5d713a66ec8f2b88b8f830b8",
          user: "5d7a514b5d2c12c7449be046",
          createdAt: "2019-11-20T10:05:11.650Z",
          __v: 0
        }
      ],
      id: "5d713a66ec8f2b88b8f830b8"
    },
    {
      location: {
        type: "Point",
        coordinates: [-71.104028, 42.350846],
        formattedAddress: "233 Bay State Rd, Boston, MA 02215-1405, US",
        street: "233 Bay State Rd",
        city: "Boston",
        state: "MA",
        zipcode: "02215-1405",
        country: "US"
      },
      careers: ["Web Development", "UI/UX", "Business"],
      photo: "no-photo.jpg",
      housing: true,
      jobAssistance: true,
      jobGuarantee: false,
      acceptGi: true,
      _id: "5d713995b721c3bb38c1f5d0",
      user: "5d7a514b5d2c12c7449be045",
      name: "Devworks Bootcamp",
      description:
        "Devworks is a full stack JavaScript Bootcamp located in the heart of Boston that focuses on the technologies you need to get a high paying job as a web developer",
      website: "https://devworks.com",
      phone: "(111) 111-1111",
      email: "enroll@devworks.com",
      createdAt: "2019-11-20T10:05:07.438Z",
      slug: "devworks-bootcamp",
      __v: 0,
      averageCost: 9000,
      averageRating: 9,
      courses: [
        {
          scholarshipAvailable: false,
          _id: "5d725c84c4ded7bcb480eaa0",
          title: "Full Stack Web Development",
          description:
            "In this course you will learn full stack web development, first learning all about the frontend with HTML/CSS/JS/Vue and then the backend with Node.js/Express/MongoDB",
          weeks: "12",
          tuition: 10000,
          minimumSkill: "intermediate",
          bootcamp: "5d713995b721c3bb38c1f5d0",
          user: "5d7a514b5d2c12c7449be045",
          createdAt: "2019-11-20T10:05:11.648Z",
          __v: 0
        },
        {
          scholarshipAvailable: false,
          _id: "5d725a4a7b292f5f8ceff789",
          title: "Front End Web Development",
          description:
            "This course will provide you with all of the essentials to become a successful frontend web developer. You will learn to master HTML, CSS and front end JavaScript, along with tools like Git, VSCode and front end frameworks like Vue",
          weeks: "8",
          tuition: 8000,
          minimumSkill: "beginner",
          bootcamp: "5d713995b721c3bb38c1f5d0",
          user: "5d7a514b5d2c12c7449be045",
          createdAt: "2019-11-20T10:05:11.647Z",
          __v: 0
        }
      ],
      id: "5d713995b721c3bb38c1f5d0"
    }
  ]
};

Finally, here is a CodeSandbox demo.最后,这里是一个CodeSandbox演示。

You're setting an Object to the state , set the data array instead :您将 Object 设置为state ,而是设置数据数组:

useEffect(() => {
    setState(api.data);
    //console.log(state)
  }, [state]);

and return something from mapping() :并从mapping()返回一些东西:

const maping = () => {
    return state.map((item, index) => ( ...
  }

As @Taki mentioned, you have to set the array data to your state, and you cannot render object as your children in react.正如@Taki 提到的,您必须将数组data设置为您的状态,并且您无法在您的孩子做出反应时渲染object Assuming that you want to render all the list's name, you have to write item.name in your maping function, also remember to return your map function.假设你想渲染所有列表的名称,你必须在你的maping函数中写入item.name ,还要记得返回你的map函数。

I've removed the state from your useEffect deps array.我已经从你的useEffect deps 数组中删除了state

useEffect(() => {
  setState(api.data);
}, []);

const maping = () => {
  return state.map((item, index) => <h3 key={index}>{item.name}</h3>);
};

The only thing you are lacking is the return statement. 您唯一缺少的是return语句。

In addition, you should not return the entire item object, as you should be returning a string or number value to be displayed on the DOM. 另外,您不应返回整个item对象,因为您应返回要在DOM上显示的stringnumber值。 You might want to use the id rather than the index for the key attribute. 您可能要使用id而不是索引作为key属性。

const maping = () => {
  return state.map((item, index) => <h3 key={item._id}>{item.name}</h3>);
};

Another thing to take note is that, you should not nest your <h3> tags within an empty <h2> tag, as it is not an appropriate HTML statement. 需要注意的另一件事是,您不应将<h3>标记嵌套在空的<h2>标记内,因为它不是适当的HTML语句。 You might nest in within a <div> tag, or react fragment , as denoted by the shorthand syntax <></> . 您可以嵌套在<div>标记内,或对片段进行反应 ,如速记语法<></>

return (
  <div className="App">
    <h3> json data rendering test</h3>
    <>{maping()}</>
  </div>
);

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

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