简体   繁体   English

如何渲染多个插入 JSX 的组件?

[英]How can I render multiple components interpolating JSX?

I am working on a website that uses an API from NYT and I am stuck trying to render all the info I have to display necessary info needed (JPG image links, links to the articles, titles to the articles, the dates to the articles).我正在一个使用 NYT 的 API 的网站上工作,我被困在试图呈现我必须显示所需信息的所有信息(JPG 图像链接、文章链接、文章标题、文章日期) .

I have all my info stored in a variable called postNY and retrieved all info(from API) into these arrays:我将所有信息存储在一个名为 postNY 的变量中,并将所有信息(来自 API)检索到这些 arrays 中:

const [postNY, setPostNY] = useState({
    images: [],
    links: [],
    titles: [],
    sections: [],
    dates: [],
    summaries: []
})
// NOTE: OBJARR IS FROM API
// GET IMG
var imgs = []
for (var key in Object.entries(objArr)[3][1]) {
    var obj = Object.entries(objArr)[3][1][key]
    Object.entries(obj['media']).forEach(elem => {
        imgs.push(elem[1]['media-metadata'][2].url)
    }
    )
}

// GET LINKS
var urls = []
Object.entries(objArr)[3][1].forEach(elem => urls.push(elem.url))


// GET TITLES
var titles = []
Object.entries(objArr)[3][1].forEach(elem => titles.push(elem.title))


// GET SECTION TAG
var sections = []
Object.entries(objArr)[3][1].forEach(elem => sections.push(elem.section))


// GET PUBLISHED DATE
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var dates = []
Object.entries(objArr)[3][1].forEach(elem => {
    var myDate = new Date(elem.published_date);
    dates.push(myDate.toLocaleDateString("en-US", options))
})


// GET BRIEF SUMMARIES
var summaries = []
Object.entries(objArr)[3][1].forEach(elem => summaries.push(elem.abstract));


// setPostNY
setPostNY({
    images: imgs,
    links: urls,
    titles: titles,
    sections: sections,
    dates: dates,
    summaries: summaries
})

Then this is where my problem occurs.那么这就是我的问题发生的地方。 I try to render the info like this into JSX:我尝试将这样的信息呈现到 JSX 中:

const renderEverything = () => {
    const renderImgs = postNY.images.map((img) => <img src={img}></img>)
    const renderSummaries = postNY.summaries.map((summary) => <p className="desc">{summary}</p>)
    const renderLinks = postNY.links.map((link) => <p>{link}</p>)
    const renderTitles = postNY.titles.map((title) => <h2>{title}</h2>)
    const renderDates = postNY.dates.map((date) => <p>{date}</p>)
    const renderSections = postNY.sections.map((section) => <a href="#">{section}</a>)

    return (
        <div className="container">
            {renderImgs}
            {renderSummaries}
            {renderLinks}
            {renderTitles}
            {renderDates}
            {renderSections}
        </div>
    )
}

JSX: JSX:

return (
        <div className="page-content">
            
            {renderEverything}
            
        </div>
        
    )

This returns nothing to the site.这不会向站点返回任何内容。 I am stuck on how to implement showing ALL these things in the array onto the site.我被困在如何实现将数组中的所有这些东西显示到网站上。 Each array is ordered correctly, what I am trying to display on the site is this(into each of their own containers):每个数组都正确排序,我想在网站上显示的是这个(到他们自己的每个容器中):

1: postNY.images[0], postNY.links[0], postNY.titles[0], postNY.sections[0], postNY.dates[0], postNY.summaries[0] 1:postNY.images[0]、postNY.links[0]、postNY.titles[0]、postNY.sections[0]、postNY.dates[0]、postNY.summaries[0]

2: postNY.images[1], postNY.links[1], postNY.titles[1], postNY.sections[1], postNY.dates[1], postNY.summaries[1] 2:postNY.images[1]、postNY.links[1]、postNY.titles[1]、postNY.sections[1]、postNY.dates[1]、postNY.summaries[1]

ETC... ETC...

Are there any approaches I can take?有什么我可以采取的方法吗?

Here is the full code:这是完整的代码:

import React, {useState,useEffect} from 'react'
import '../PageContent/PageContent.css'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import { faThumbsUp, faHeart} from '@fortawesome/free-solid-svg-icons'



const PageContent = (props) => {


    const [postNY, setPostNY] = useState({
        images: [],
        links: [],
        titles: [],
        sections: [],
        dates: [],
        summaries: []
    })


    useEffect(() => {
        fetch("https://api.nytimes.com/svc/mostpopular/v2/viewed/1.json?api-key=uCErKitNpdG7E7ma9rT0IxEGZ4xKs8Vw")
        .then((res) => res.json())
        .then((objArr)=>{

            // GET IMG
            var imgs = []
             for (var key in Object.entries(objArr)[3][1]) {
                var obj = Object.entries(objArr)[3][1][key]
                Object.entries(obj['media']).forEach(elem => 
                {
                    imgs.push(elem[1]['media-metadata'][2].url)
                }
                    ) 
            }
            
             // GET LINKS
            var urls = []
            Object.entries(objArr)[3][1].forEach(elem => urls.push(elem.url))
            

            // GET TITLES
            var titles = []
            Object.entries(objArr)[3][1].forEach(elem => titles.push(elem.title))
            

            // GET SECTION TAG
            var sections = []
            Object.entries(objArr)[3][1].forEach(elem => sections.push(elem.section))
            
            
            // GET PUBLISHED DATE
            var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
            var dates = []
            Object.entries(objArr)[3][1].forEach(elem => 
               { 
                   var myDate  = new Date(elem.published_date); 
                   dates.push(myDate.toLocaleDateString("en-US", options))
                }
                )
            

            // GET BRIEF SUMMARIES
            var summaries = []
            Object.entries(objArr)[3][1].forEach(elem => summaries.push(elem.abstract));
            
            setPostNY({
                images: imgs,
                links: urls,
                titles: titles,
                sections: sections,
                dates: dates,
                summaries: summaries
            })
        })
        
        
    })

    const renderEverything = () => {
        const renderImgs = postNY.images.map((img) => <img src={img}></img>)
        const renderSummaries = postNY.summaries.map((summary) => <p className="desc">{summary}</p>)
        const renderLinks = postNY.links.map((link) => <p>{link}</p>)
        const renderTitles = postNY.titles.map((title) => <h2>{title}</h2>)
        const renderDates = postNY.dates.map((date) => <p>{date}</p>)
        const renderSections = postNY.sections.map((section) => <a href="#">{section}</a>)

        return (
            <div className="container">
                {renderImgs}
                {renderSummaries}
                {renderLinks}
                {renderTitles}
                {renderDates}
                {renderSections}
            </div>
        )
    }
        
        
        

        
        
        
    
    

    return (
        <div className="page-content">
            
            {renderEverything}
            
        </div>
        
    )
}

export default PageContent

Make sure you are actually calling the function that returns the content.确保您实际调用的是返回内容的 function。 you have {renderEverything} it should be {renderEverything()}你有{renderEverything}它应该是{renderEverything()}

    return (
        <div className="page-content">
            {renderEverything()}
        </div>
    )

Also on useEffect provide an empty array of dependencies to make it run once otherwise it will run continuously.同样在useEffect上提供一个空的依赖数组以使其运行一次,否则它将连续运行。

useEffect(() => {
    // your fetch code
}, []) // add this

just as a note, using Object.entries makes the code you are writing quite verbose.就像注释一样,使用Object.entries会使您编写的代码非常冗长。 javascript has a lot of features that make it easy to iterate objects and Arrays. javascript 具有许多功能,可以轻松迭代对象和 Arrays。 You don't have to use indexing when you can say the name of the object.当您可以说出 object 的名称时,您不必使用索引。 you can convert this你可以转换这个

var imgs = []
for (var key in Object.entries(objArr)[3][1]) {
    var obj = Object.entries(objArr)[3][1][key]

    Object.entries(obj['media']).forEach(elem => {
        imgs.push(elem[1]['media-metadata'][2].url)
    })
}

to this对此

let imgs = objArr.results.map( (entry) => entry.media?.[0]?.['media-metadata'][2].url )

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

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