【问题标题】:React TypeError: Cannot read property 'map' of undefinedReact TypeError:无法读取未定义的属性“地图”
【发布时间】:2020-09-16 17:28:54
【问题描述】:

更新

我正在学习反应,所以使用 omdbapi api 想要获取数据但得到 TypeError: Cannot read property 'map' of undefined

请帮忙解决这个问题

class App extends React.Component {
  constructor(){
    super()
    this.state={
      data:[],
    }
  }
  componentDidMount(){
    fetch('http://www.omdbapi.com/?i=tt3896198&apikey=key123')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
     this.setState({
       data:findresponse.movie
     })
      })
  }
  render() {
  return (
    <div>
      {this.state.data.map((dynamicData)=> 
      <div>
        <img src={dynamicData.Poster} alt=""/>
        <p>{dynamicData.title} </p>
        <p>{dynamicData.Released} </p>
      </div>
      )}
    </div>
  )
}
}

在下面的回答之后,我更新了源代码,现在 html 输出为空白,但在 console.log 中显示输出

我想循环播放 20 部电影

componentDidMount(){
    fetch('http://www.omdbapi.com/?apikey=mykey&s=batman')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
      console.log(findresponse)
     this.setState({
      data:[findresponse]
     })
      })
  }
  render() {
  return (
    <div>
      {this.state.data && this.state.data.map((dynamicData , key)=> 
      <div key={key}>
        <img src={dynamicData.Poster} alt=""/>
        <p>{dynamicData.Title} </p>
        <p>{dynamicData.Released} </p>
      </div>
      )}
    </div>
  )
}
}

【问题讨论】:

  • 你的findresponse.movie是什么样的?
  • 是的,检查findresponse.movie 的对象形状以确保它是一个可以被映射 的数组。另外,请记住为每个映射元素提供一个唯一的反应键。

标签: reactjs api


【解决方案1】:

问题:

按照api,它只返回一个电影对象,而且它也没有movie键,所以你不能通过mapmap它应该是数组。

// response is taken from http://www.omdbapi.com/?i=tt3896198

{
    "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 & 56 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": "537,920",
    "imdbID": "tt3896198",
    "Type": "movie",
    "DVD": "22 Aug 2017",
    "BoxOffice": "$389,804,217",
    "Production": "Walt Disney Pictures",
    "Website": "N/A",
    "Response": "True"
}

解决方案:

发件人:来自http://www.omdbapi.com/?i=tt3896198

// as there is no `movie` key change `findresponse.movie` to `findresponse`

// if you want to use it as array for only one object
this.setState({
    data:[findresponse]
    // OR
    data : [...this.state.data , findresponse] // <--- If you want pushing result with previous 
})

// suggested
this.setState({
    data : findresponse
})

对于:http://www.omdbapi.com/?apikey=YOUR_KEY&s=Batman,你可以使用下面的

this.setState({
    data : findresponse.Search
})

【讨论】:

  • 更改 setState 电影数据后显示如何循环数据,就像我想要 10 部电影一样,因为现在只有一部电影显示
  • @Viking,如果您通过 id http://www.omdbapi.com/?i=tt3896198 搜索,您将始终只获得一部电影。
  • 我已经更改了 api 路径 fetch('omdbapi.com/?apikey=mykey&s=batman') 并在 console.log(findresponse) 中打印数据正在获取但在 html 上它的总空白
    {this.state.data && this.state.data.map((dynamicData , key)=>

    {dynamicData.Title}

    {dynamicData.Released}

    )}
  • 对于omdbapi.com/?apikey=mykey&s=batman%27 使用this.setState({ data:findresponse.Search })
【解决方案2】:

先尝试检查数据是否未定义:

{this.state.data && this.state.data.map((dynamicData)=> 
  <div>
    <img src={dynamicData.Poster} alt=""/>
    <p>{dynamicData.title} </p>
    <p>{dynamicData.Released} </p>
  </div>
  )}

【讨论】:

    猜你喜欢
    • 2017-03-26
    • 2021-09-09
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2021-01-06
    • 2017-11-25
    • 2019-03-19
    相关资源
    最近更新 更多