Estoy trabajando con React + JS en una aplicación para generar noticias del NYTimes ( https://developer.nytimes.com/ ). Bueno, el caso es que quiero renderizar lo más visto en los últimos 7 días, pero organizado por categorías o secciones. Y tengo el problema con la representación de mis secciones.
Aquí my app.js
:
import React, {useEffect, useState} from "react"; import ListOfSections from "./components/ListOfSections"; import getSections from "./services/getSections"; import Navbar from "./shared/Navbar/Navbar"; function App() { const [section, setSection] = useState([]); useEffect(() => { getSections().then(sections=>setSection(sections)); }, []) return ( <div> <Navbar/> <ListOfSections section={section}></ListOfSections> </div> ); } export default App;
Aquí mi componente ListOfSections
:
import React from 'react'; import Section from './Section'; export default function ListOfSections ({section}) { return ( <div className="container_list_sections mt-4 ml-4"> { section.map(({section})=> <Section section={section} /> ) } </div> ) };
Y aquí mi componente de Section
:
import React from 'react'; export default function Section ({section}) { return ( <div> <h1 className="section-container mr-4">{section}</h1> </div> ) };
Bueno, el problema es que cuando hago console.log(section)
en el componente Section
, me devuelve undefined
. Pero si hago console.log(section)
en el componente ListOfSections
, ha recibido la información de los accesorios. Entonces... ¿por qué cuando paso la section
de accesorios de ListOfSections
a Section
, no está definida? ¿Dónde está el error? No entiendo. El resultado por el momento es este:
Gracias :)
Su useEffect
debería tener el siguiente aspecto:
const [sections, setSections] = useState([]); ... useEffect(() => { getSections().then(sections=>setSections(sections)); }, [])
Cuando recupera los datos, parece ser una serie de sections
, por lo que debe ser un plural.
Entonces, cuando pasas sections
como apoyo, debería ser:
<ListOfSections sections={sections}/>
Lo que luego le permite mapear en <ListOfSections>
export default function ListOfSections ({sections}) { return ( <div className="container_list_sections mt-4 ml-4"> { sections.map(section => <Section section={section} /> ) } </div> ) };
Para los mapas, también debe establecer una key
, puede leer más aquí