如何在数组 React 组件中使用地图打印 JSON 数据

我在 React 数据文件中有一个这样的数组,我正在使用该.map()方法在组件中加载 JSON 数据ProjectItem.js。


打印嵌套 JSON 对象的最有效方法是什么?我现在想在项目数组中打印标题,以便我可以调试它,在浏览器上显示它。我在检查员中看不到<div className="title"></div>,正确的功能是什么?


数据.json


{

"projects": [

    {

        "title": "Projecttitle1",

        "category": "frontend development",

        "description": "",

        "desktop": [],

        "mobile": []

    }

  ]

}

ProjectItem.js


import React from 'react';

import './ProjectItem.scss';

import useWindowWidth from '../../Hooks/useWindowWidth.js';

import { projects } from '../../data'


import desktopImage from '../../Assets/Images/Projects/Desktop/123.jpg';

import mobileImage from '../../Assets/Images/Projects/Mobile/123_square.jpg'



const ProjectItem = ({ viewProject }) => {


const imageUrl = useWindowWidth() >= 650 ? desktopImage : mobileImage;


const { windowWidth } = useWindowWidth();

return(

    <div className="projectItem" style={{ backgroundImage: `url(${ imageUrl })`}}>

        {windowWidth >= 650 &&( 

            <>

            <div className="title">

                {projects.map((data, key)=>{

                        console.log(key);

                    return(

                        <div key={key}>

                        {data.title}

                        </div>

                    );

                })} 

            </div>

            <div className="viewProject">{viewProject}</div>

            </>

        )}  

    </div>

    );

}; 


export default ProjectItem

安慰:


空的


狐的传说
浏览 121回答 1
1回答

德玛西亚99

我假设import { projects } from '../../data'是这样的:export const data = {  projects: [    {      title: "Project title 1",      category: "frontend development",      description: "",      desktop: [],      mobile: []    }  ]};projects所以当你映射这个对象时,你需要像这样引用属性data.projects.map()。例子:数据.jsexport const data = {  projects: [    {      title: "Project title 1",      category: "frontend development",      description: "",      desktop: [],      mobile: []    },    {      title: "Project title 2",      category: "frontend development",      description: "",      desktop: [],      mobile: []    }  ]};应用程序.jsimport React from "react";import { data } from "./data";export default function App() {  return (    <div>      {data.projects.map((project, key) => {        return <p key={key}>{project.title}</p>;      })}    </div>  );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript