简体   繁体   English

如何在 React 组件中使用数组映射 JSON 数据

[英]How to map JSON data with array in React component

I have an array like this in React data file and I'm using the .map() method to load JSON data in component ProjectItem.js .我在 React 数据文件中有一个这样的数组,我正在使用.map()方法在组件ProjectItem.js加载 JSON 数据。

question 1: solved What is the most efficient way to find out if my code contains a value?问题 1:已解决找出我的代码是否包含值的最有效方法是什么? '{data.title} isn't showing on my page at the moment. '{data.title} 目前没有显示在我的页面上。 I've tried on applying some code as per document please have a look and help me.我已经尝试根据文档应用一些代码,请查看并帮助我。

* question 2: What is the most efficient way to print nested JSON object? *问题 2:打印嵌套 JSON 对象的最有效方法是什么? I now want to print the title in projects array so I can debug it.我现在想在项目数组中打印标题,以便我可以调试它。 show on browser.在浏览器上显示。 I can't see in inspector console.log(key) isn't showing on console (something is going wrong with the function).我在检查器中看不到 console.log(key) 没有显示在控制台上(函数出了点问题)。

Data.json数据.json

{
"projects": [
    {
        "title": "Projecttitle",
        "category": "frontend development",
        "description": "",
        "desktop": [],
        "mobile": []
    }
  ]
}

ProjectItem.js项目项目.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

Console:安慰:

empty空的

You can use the length property of the array to determine if the array is empty or not.您可以使用数组的length属性来确定数组是否为空。

const emptyArray = [];
const notEmptyArray = [1,2,3];

console.log(!emptyArray.length); // => true;
console.log(!notEmptyArray.length); // => false;

您可以使用Array.prototype.includes()来检查元素是否在数组中。

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

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