【问题标题】:¿My error is 'data.map' or is my request api? [duplicate]¿ 我的错误是“data.map”还是我的请求 api? [复制]
【发布时间】:2021-02-28 02:02:35
【问题描述】:

我的代码在data.map中给了我一个错误,但我不知道现在是怎么回事。

export const GetFilms = () => {


    const getPoster = async() =>{

    const url = 'https://www.omdbapi.com/?i=tt3896198&apikey=********';
    const resp = await fetch( url );
    const data = await resp.json();

    const poster = data.map( Poster => {
          return {
              id: Poster.imdbID
          };
    })

    console.log(poster);
    }

    getPoster();

    return(
        <div></div>
    )
   
}


export default GetFilms;

我给出的控制台错误是Unhandled Rejection (TypeError): data.map is not a function .. 谢谢你的时间。

【问题讨论】:

  • 什么是data?我假设它不是一个数组。根据他们的文档,data 是一个对象,所以map 不是一个函数是有道理的。
  • 我会用 console.log(data) 来调试它。很可能来自 API 的响应是一个字典,该字典在其中一个字段中包含一个数组,这是您要在其上运行 map 函数的字段。

标签: javascript reactjs rest


【解决方案1】:

查看他们的示例响应,看起来您只是返回了一个普通对象:

const data = {"Title":"Guardians of the Galaxy Vol. 2","Year":"2017","Rated":"PG-13","Released":"05 May 2017","Runtime":"136 min","Genre":"Action, Adventure, Comedy, Sci-Fi","Director":"James Gunn","Writer":"James Gunn, Dan Abnett (based on the Marvel comics by), Andy Lanning (based on the Marvel comics by), Steve Englehart (Star-Lord created by), Steve Gan (Star-Lord created by), Jim Starlin (Gamora and Drax created by), Stan Lee (Groot created by), Larry Lieber (Groot created by), Jack Kirby (Groot created by), Bill Mantlo (Rocket Raccoon created by), Keith Giffen (Rocket Raccoon created by), Steve Gerber (Howard the Duck created by), Val Mayerik (Howard the Duck created by)","Actors":"Chris Pratt, Zoe Saldana, Dave Bautista, Vin Diesel","Plot":"The Guardians struggle to keep together as a team while dealing with their personal family issues, notably Star-Lord's encounter with his father the ambitious celestial being Ego.","Language":"English","Country":"USA","Awards":"Nominated for 1 Oscar. Another 15 wins & 57 nominations.","Poster":"https://m.media-amazon.com/images/M/MV5BNjM0NTc0NzItM2FlYS00YzEwLWE0YmUtNTA2ZWIzODc2OTgxXkEyXkFqcGdeQXVyNTgwNzIyNzg@._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"7.6/10"},{"Source":"Rotten Tomatoes","Value":"85%"},{"Source":"Metacritic","Value":"67/100"}],"Metascore":"67","imdbRating":"7.6","imdbVotes":"573,212","imdbID":"tt3896198","Type":"movie","DVD":"N/A","BoxOffice":"$389,813,101","Production":"Marvel Studios, Walt Disney Pictures","Website":"N/A","Response":"True"}

const poster = {
    id: data.imdbID
};

console.log(poster);

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 2021-08-20
    • 2012-03-09
    • 2022-01-10
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多