Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
React no puede acceder a la matriz dentro del objeto

Estoy tratando de acceder a una matriz dentro de un objeto. La forma del objeto es:

 {memes : { data: {memes: Array(100)} success: true }}
 import React from 'react'; import API from './functions/api'; import styles from './App.module.css'; class App extends React.Component { state = { memes: [] } componentDidMount(){ API.get().then( res => { // axios function returns Object const memes = res.data this.setState({ memes }) } ) } displayMemes(){ console.log( this.state.memes ); // memes: { // data: { // memes: Array(100) // } // } this.state.memes.data.memes.forEach( meme => { // Cannot read properties of undefined (reading 'forEach')... }); } render(){ return( <div className={ styles.container }> { this.displayMemes() } </div> ) } } export default App;

Claramente no se que estoy haciendo mal, soy bastante nuevo en esto, la solución tiene que ser simple.

Estoy tratando de obtener datos de una API abierta ('https://api.imgflip.com/get_memes') para practicar la implementación de diferentes tipos de aplicaciones React.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Llamar a una API es una acción asíncrona que tarda algún tiempo en resolverse.
Puede inicializar memes con un valor nulo primero.

 state = { memes: null }

Compruebe si memes no es nulo antes de llamar a displayMemes para evitar llamarlo antes de obtener la respuesta de la API.

 render(){ return( <div className={styles.container}> {this.state.memes && this.displayMemes()} </div> ) }
about 4 years ago · Juan Pablo Isaza Report

0

 const memes = res.data.memes this.setState({ memes })
about 4 years ago · Juan Pablo Isaza Report

0

La función forEach siempre devuelve undefined después de atravesar la matriz. Cámbielo a map que devuelve una matriz.

 class App extends React.Component { state = { memes: null, isLoading: true }; componentDidMount() { fetch("https://api.imgflip.com/get_memes") .then((res) => res.json()) .then((memes) => { this.setState({ memes }); this.setState({ isLoading: false }); }); } displayMemes() { return this.state.memes.data.memes.map((meme) => { return <div>{meme.name}</div>; }) } render() { return this.state.isLoading ? "No memes" : <div>{this.displayMemes()}</div>; } } ReactDOM.render(<App />, document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Agregué isLoading para llamar a displayMemes cuando se hayan obtenido datos.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!