Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

377
Vistas
El método map() de JavaScript está fallando con el error "el mapa no es una función"

Estoy tratando de obtener una lista de elementos de la matriz de una API, pero cuando uso la función de mapa en los elementos, dice que el mapa no es una función.

 import React from 'react' import { useState } from 'react'; const axios = require('axios'); const Api = () => { const [items, setItems] = useState([]); const getUser = async () => { try { const response = await axios.get('http://localhost:5000/api/products'); console.log(response); setItems (JSON.stringify(response)); } catch (error) { console.error(error); } } return ( <div> <button onClick={getUser}> Fetch Data</button> <br /> <br /> <br /> {items} </div> )

}

 export default Api
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

No deberías usar JSON.stringify . ya que ya es objeto

Simplemente cámbielo al siguiente código

 const response = await axios.get('http://localhost:5000/api/products'); setItems(response.data);
about 4 years ago · Juan Pablo Isaza Denunciar

0

El método axios.get() devuelve el object y no puede usar el método map() en un objeto como se ha definido en el prototype de una matriz. Puede encontrar más detalles de Array.prototype.map() aquí

En primer lugar, comprendamos qué devuelve el método axios.get() .

 { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lower cased and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} }

Puede encontrar más detalles aquí . Eso significa que los datos reales que está buscando residen en response.data . Necesitas extraerlo.

 const { data } = response;

Ahora necesita analizar y procesar los data en el formato renderizable de React .

about 4 years ago · Juan Pablo Isaza Denunciar

0

Funcionó por setItems (response.data)

 import React from 'react' import { useState } from 'react'; const axios = require('axios'); const Api = () => { const [items, setItems] = useState([]); const getItems = async () => { try { const response = await axios.get('http://localhost:5000/api/products'); console.log(response.data); setItems (response.data); console.log(response.data) } catch (error) { console.error(error); } } return ( <div> <button onClick={getItems}> Fetch Data</button> <br /> <br /> <br /> {items.map((item)=>( <div > <h1>{item.name}</h1> <h2>{item.price}</h2> </div> ))} </div> )

}

 export default Api
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda