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

150
Views
Error de búsqueda y función en AJAX y llamada de API en reactjs

Recibo un error de items.map is not a function cuando obtengo el archivo alojado desde unsplash.

No estoy seguro de si el problema proviene del .map o de obtener el archivo de la fuente.

A continuación se muestra mi código y también aquí está el código de sandbox completo https://codesandbox.io/ .

 import { React, useState, useEffect } from "react"; function MyComponent() { const [error, setError] = useState(null); const [isLoaded, setIsLoaded] = useState(false); const [items, setItems] = useState([]); useEffect(() => { fetch( "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U" ) .then((res) => res.json()) .then( (result) => { setIsLoaded(true); setItems(result); }, (error) => { setIsLoaded(true); setError(error); } ); }, []); if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return ( <ul> {items.map((item) => <li key={item.results.id}> {item.results.description} </li> )} </ul> ); } } export default MyComponent;
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Parece que la respuesta JSON es un objeto y no una matriz. Cuando actualiza el estado de los items con un objeto, ya no es mapeable.

 // 20220209004834 // https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U#f3f3f3 { "total": 10000, "total_pages": 1000, "results": [ { "id": "_LuLiJc1cdo", "created_at": "2016-06-06T01:08:36-04:00", "updated_at": "2022-02-08T13:00:46-05:00", "promoted_at": "2016-06-06T01:08:36-04:00", ... "description": "follow @kalenemsley on ig", ... }, ... ], ... }

Probablemente desee la propiedad de matriz de results para su estado.

 useEffect(() => { fetch("....") .then((res) => res.json()) .then( (result) => { setIsLoaded(true); setItems(result.results); }, (error) => { setIsLoaded(true); setError(error); } ); }, []);

Luego , al mapear cada elemento, accede a las propiedades correctamente

 <ul> {items.map((item) => <li key={item.id}> {item.description} </li> )} </ul>

Edite fetch-and-function-error-on-ajax-and-apis-call-on-reactjs

over 4 years ago · Santiago Trujillo 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!