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

时间:2019-11-25 15:23:04

标签: javascript json reactjs

我正在研究要向用户显示结果的项目,但是在渲染JSON对象数据时遇到了麻烦;它给出了错误状态:

  

“地图”不是函数

App.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;

这是我的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"
    }
  ]
};

最后,这是一个CodeSandbox演示。

3 个答案:

答案 0 :(得分:2)

您正在将对象设置为state,而是设置数据数组:

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

并从mapping()返回值:

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

答案 1 :(得分:1)

正如@Taki所述,您必须将数组data设置为您的状态,并且您的孩子在做出反应时无法渲染object。假设您要呈现列表的所有名称,则必须在item.name函数中编写maping,还要记住要返回map函数。

我已从您的state deps阵列中删除了useEffect

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

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

答案 2 :(得分:0)

您唯一缺少的是std::conditional_t语句。

此外,您不应返回整个static const int val = std::conditional_t<N < M, commondivs<N,(M-N)>, commondivs<(N-M),M>>::val; 对象,因为您应该返回要在DOM上显示的returnitem值。您可能要使用string属性而不是number属性的索引。

id

要注意的另一件事是,您不应该将key标记嵌套在一个空的const maping = () => { return state.map((item, index) => <h3 key={item._id}>{item.name}</h3>); }; 标记内,因为它不是适当的HTML语句。您可以嵌套在<h3>标记或react fragment中,如简写语法<h2>所示。

<div>