如何在React中访问API对象属性?

问题描述 投票:0回答:1

我在使用React访问对象时遇到问题。该对象是使用tMDB API生成的。一旦我可以访问该对象,我想将ID prop传递给子组件。

家:

import React, {Component} from 'react'
import Movie from '../components/Movie'
import '../index.css'

class Home extends Component{

  constructor(props) {
    super(props)
    this.state = {
      movie: [],
    }
  }

  componentDidMount() {
    this.fetchData()
  }

  fetchData(){
    fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=17c21a1abd8ae7be6ee8986389011906')
      .then(response=> response.json())
      .then( ({results: movie}) => this.setState({movie}))
  }

  render() {

    console.log(this.state.movie[1].id);

    return(
        <div className="main">
          <div>

         </div>
        </div>
    )
  }
}

export default Home

这会输出TypeError:无法读取未定义的属性“id”

如果我将this.state.movie[1].id更改为this.state.movie[1],我可以看到完整对象及其属性,但无法访问代码中的子属性。

我认为问题可能是React正在渲染状态两次,因为在影片对象正上方有一个“未定义”对象。如果是这样,我该如何解决?

安慰:

Array(0)
length
:
0
__proto__
:
Array(0)
Home.js:26 

Array(20)
0:
{vote_count: 4600, id: 284053, video: false, vote_average: 7.4, title: "Thor: Ragnarok", …}
1:
{vote_count: 2314, id: 284054, video: false, vote_average: 7.4, title: "Black Panther", …}
2:
{vote_count: 771, id: 337167, video: false, vote_average: 6.3, title: "Fifty Shades Freed", …}
...
javascript json reactjs object
1个回答
1
投票

您必须验证电影是否为空,因为您的api调用需要一些时间才能获得响应。请记住,每次使用setState修改状态时,react会重新呈现组件

render() {
    if (this.state.movie.length === 0) {
     return (<div>Loading data...</div>)
    }

    console.log(this.state.movie[1].id);

    return(
        <div className="main">
          <div>

         </div>
        </div>
    )
  }
© www.soinside.com 2019 - 2024. All rights reserved.